Any other ways to write a dynamic array?

closed account (NCRLwA7f)
I have an assignment for a class where I need to read in values from a text file. They are just simple integers each per line.
The instructions state that I cannot use brackets [] in my code with the exception of declaring a dynamic array. For this example, we will make the size of the array 20.
(Assuming my Text file is open and working correctly)

1
2
3
4
5
6
7
8
  int size = 20;
  int* myPtr;
  
  myPtr = new int[size]

  for(int i = 0; i < size; i++)     
     inFile >> myPtr[i];

This is the only way I was able to make this work, the problem is that I am using brackets [] in the rest of the code and not when I initially declared "new int[size]"

is there another way that I can write this by not using myPtr[i]

would it be possible to increment the address of myPtr another way such as myPtr = myPtr + 1

I tried this and It did not work very well
1
2
3
4
5
for(int i = 0; i < size; i++)
{
  inFile >> *p;
  p = p + 1;
}


any Ideas would be helpful, thank you for your time.
**All other examples I have searched for on Google and In my textbook, use this type "myPtr[i]"
closed account (48T7M4Gy)
Seeing that you are on the right track:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

int main()
{
    int size = 5;
    
    int *ptr = new int[size];
    
    for(int i = 0; i < size; ++i)
    {
        *ptr = i + 77;
        ptr++;
    }
    
    ptr = ptr - size; // MOST IMPORTANT TO RESET TO [0]-th element
    for(int i = 0; i < size; ++i)
    {
        std::cout << i << '\t' << *ptr << '\n';
        ptr++;
    }
    return 0;
}


0	77
1	78
2	79
3	80
4	81
Program ended with exit code: 0
Last edited on
closed account (48T7M4Gy)
And:
1
2
3
4
5
6
    std::cout << "Which element do you want? ";
    int n = 0;
    std::cin >> n; // NO CHECK - BE CAREFUL
    
    ptr = ptr - size;
    std::cout << *(ptr + n) << '\n';
closed account (48T7M4Gy)
Afterthought: instead of using 'n' as a variable name, 'offset' is more conventional and self-documenting
1
2
3
4
5
6
7
8
9
10
11
12
myptr[x]
is the same as
*(myptr+x)

or you can iterate
type *mp = myptr;
for(x ...)
  {
     process(*mp); 
     mp++; //you can roll this into one statement with process but watch out for accidentally incrementing the data by order of operations issues.  
   //mp is a throw-away pointer that moves as you go. myptr is  unchanged.
   }

Last edited on
closed account (NCRLwA7f)
Thank you Kemort and jonnin I really appreciate the help. This helped me out on my program
Topic archived. No new replies allowed.