-5

I need help trying to figure out why my pointer array is not working. I am incrementing the pointer address and the I. My console windows is just hanging.

int *arr = new int[10];
int i = 0;

while (i < 10){
    *arr = i;  // assign the value of arr to i
    arr++;     // increment the pointer by 1
    i++;       // increment i
}

delete[] arr; 
paddy
  • 60,864
  • 6
  • 61
  • 103
runners3431
  • 1,425
  • 1
  • 13
  • 30

1 Answers1

6

In this declaration

int *arr = new int[10];

pointer arr is initialized by the address of the first element of the dynamically allocated array.

In the while loop

while (i < 10){
    *arr = i;  // assign the value of arr to i
    arr++;     // increment the pointer by 1
    i++;       // increment i
}

the pointer is incremented.

arr++;

So after the loop it points beyond the allocated array and this statement

delete[] arr;

is wrong because pointer arr does not now store the original addres of the allocated array.

I think you mean the following

const int N = 10;
int *arr = new int[N];

int i = 0;
for ( int *p = arr; p != arr + N; ++p ){
    *p = i++;  // assign the value of i to *p
}

for ( int *p = arr; p != arr + N; ++p ) std::cout << *p << ' ';
std::cout << std::endl;

delete[] arr; 
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335