The memory address of ptr is same as array after ptr=array. In other words ptr points to the memory address of array after ptr=array. So ptr will be same as array. So if you change something in array, the same change would be seen in ptr.
Try running this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
usingnamespace std;
int main()
{
int array[10] = {1,2,3,4,5,6,7,8,9,10};
int *ptr=newint[5];
ptr=array;
for(int i = 0; i<10; i++)
{
array[i] = 0; //We change the value in array
cout << ptr[i] << endl; //And see the same change in ptr
}
return 0;
}
int array[10] {1,2,3,4,5,6,7,8,9,10};
int *ptr= newint[5];
ptr=array;
At line 3, the program requests memory to store 5 integers, and the start address of that block of memory is placed in ptr. Then at line 4, ptr is reassigned to point to something else. The block of 5 integers previously requested is now lost, it cannot be accessed or deleted, as the address has been replaced with a different value.
int array[10] = { ... };
This allocates 10 consecutive integers and makes a pointer array which will point to the first element.
int *ptr = newint[5];
This allocates 5 consecutive integers and makes a pointer ptr which will point to the first element.
ptr = array;prt now points to the same integer as array. Nothing points to the old integer anymore and now we can't get it back. This is a memory leak.
int* ptr = newint[3];
// Do stuff with ptr, e.g.
ptr[0] = 1;
ptr[1] = 2;
ptr[2] = 3;
Technically speaking, this is perfectly valid syntax:
1 2
// "delete" element 1???
delete (ptr + 1); // !!
But I have no clue what sort of undefined behavior that may or may not cause (so don't try it).
The only thing you can safely delete is the whole thing, via delete[] ptr;.
What exactly are you trying to accomplish by deleting element 1?
Do you want
/* "delete" element 1 here */
std::cout << ptr[0] << '\n'; // 1
std::cout << ptr[1] << '\n'; // 3 (original element 2 gets shifted down a spot)
std::cout << ptr[2] << '\n'; // ??? (undefined; the array is 1 element smaller,
// so index 2 is out-of-bounds now)
I don't see any reason you would want to do the first one.
For the second one, you can use a loop (or standard library function) to shift the other elements over a spot and then simply "forget about" the value of the last element in your program.
For the third one, you can just write ptr[1] = int();.