I am just learning all the nuances of using pointers and have run into a sticky problem.
I am building a binary search tree. I have allocated multiple nodes (using new) and successfully placed them in the tree. My problem arises when I try to delete one of them.
I have a function called find that locates the node and returns a pointer to it and saves that pointer in a variable on the stack called node. I then have a function that attempts to delete that node.
I understand that the node was allocated with new so I should use delete to get rid of it, but when I try to delete it using delete &node;, I get an error. I think the problem is because I am trying to delete it using the variable on the stack with was not allocated with new.
How can I delete the object in memory (that was allocated with new) but using a pointer variable that is on the stack? The original variable that was used with new is long gone in another function.
My code works just fine if I just delete node; but if I understand correctly that only deletes the node variable on the stack, not the object pointed to by the variable.
Thanks for any suggestions or corrections to my thinking.
Don't say delete &node. Just say delete node. It deletes the object with the address that's stored in node. There is no way to "delete" something that's on the stack (in this case the pointer variable holding the node's address). Stack variables are "deleted" automatically when the function returns.
My code works just fine if I just delete node; but if I understand correctly that only deletes the node variable on the stack, not the object pointed to by the variable.
You misunderstand. delete ptr doesn't delete ptr, it deletes whatever ptr points to. So it's perfectly fine to say:
1 2 3 4
Node *p1, *p2; // declare two pointers
p1 = new Node; // create a new Node and point p1 to it.
p2 = p1; // Point p2 to the same Node.
delete p2; // delete the Node using p2.