Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you delete a pointer without deleting the data the pointer points to?

Tags:

c++

pointers

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?

like image 435
Faken Avatar asked May 07 '10 20:05

Faken


People also ask

What happens when you delete a pointer to a pointer?

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).

Does deleting a pointer delete the object?

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.

Can we delete a pointer?

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.


2 Answers

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.

like image 143
Cory Petosky Avatar answered Sep 19 '22 15:09

Cory Petosky


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.

like image 26
Edward Strange Avatar answered Sep 18 '22 15:09

Edward Strange