Problems with pointers
I have a Binary Search Tree that I'm making and I implemented the Insert node code as follows:
BSTNode * BST::Insert(const std::string & v){
BSTNode * node = new BSTNode(v);
if (root == NULL){
root = node;
} else if (root->value.compare(v) > 0) {
Insert(root->left, node);
//recursive insert the method
} else if (root->value.compare(v) < 0) {
Insert(root->right, node);
} else {
delete node;
return NULL;
}
size++;
return node;
}
Followed by the recursive insert method in my header file (it has private access):
void Insert(BSTNode* current, BSTNode* node){
if (current == NULL){
current = node;
} else if (current->value == node->value){
delete node;
} else if (current->value < node->value) {
Insert(current->left, node);
} else if (current->value > node->value){//if (parent->v开发者_Python百科alue < node->value) {
Insert(current->right, node);
}
}
When the recursive function sets the pointer and then returns, the changes I made to the pointer DON'T stay.
The problem here is that current
is a local variable with a copy of the value of the pointer. It's not the same variable that you pass in. If you want to modify the pointer in place, your method should accept either a pointer to the pointer or a reference to the pointer. The easiest way to do this would be to just modify current
to be a reference to a pointer. The resultant code would look like this:
void Insert(BSTNode* ¤t, BSTNode* node){
if (current == NULL){
current = node;
} else if (current->value == node->value){
delete node;
} else if (current->value < node->value) {
Insert(current->left, node);
} else if (current->value > node->value){//if (parent->value < node->value) {
Insert(current->right, node);
}
}
In general, you should keep in mind that pointers are just values which tell you the memory location of something. So they're really just numbers. And when they're passed into a function, unless there's a reference, they're passed by the value. So your function just sees the number, not the variable which contained the number.
void Insert(BSTNode*& current, BSTNode* node)
is the correct prototype for the function given. Nothing else need be changed. The reason why this is necessary is described well by Keith.
I would also add that in general you should be wary of conditionally deleting pointers passed as arguments to a function -- you're placing a burden on the code outside that function to determine whether the memory address it refers to is still valid or not. Consider use of boost's shared_ptr instead.
精彩评论