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;