I have a pointer that points to an array and another pointer referencing the same array. How do i delete any one of those pointers without killing the array such that the second undeleted pointer still works?
for example:
int* pointer1 = new int [1000];
int* pointer2;
pointer2 = pointer1;
Now i want to get rid of pointer1, how would i do it such that i can continue to access the array normaly through pointer2?
The address of the pointer does not change after you perform delete on it. The space allocated to the pointer variable itself remains in place until your program releases it (which it might never do, e.g. when the pointer is in the static storage area).
Deleting a pointer, or deleting an object (by passing a pointer to that object to delete )? The pointer to that inner object will be deleted, but the object itself won't be.
It is not safe to delete a void pointer in C/C++ because delete needs to call the destructor of whatever object it's destroying, and it is impossible to do that if it doesn't know the type.
Those pointers are on the stack; you don't have to delete them. Just ignore pointer1
and it will go away at the end of the block.
Let it go out of scope?
You don't 'delete' pointers, you delete what they point at. So if you just want to get rid of the variable 'pointer1' the only way to do that is for the scope it was created in to be terminated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With