I have a question about passing a pointer as an argument to a function.
I'm creating a binary search tree and am trying to insert a node into an empty tree. The followings are parts of my code. I cannot seem to update the root element with this. I know that something is wrong with my pointer handling. Could you tell me what I am doing wrong here?
BSTree::BSTree () {
root = NULL; // root is a private variable of type Node*.
}
// public function
void BSTree::insertNode (int v) {
// This does not insert a new node. Why?
_insertNode(root, new Node (v));
}
// private function
void BSTree::_insertNode (Node* root, Node* node) {
if (root == NULL) {
root = node;
} else {
if (node->value < root->value) {
_insertNode(root->left, node);
} else {
_insertNode(root->right, node);
}
}
}
1 2 3 4
int main () {
BSTree* bstree = new BSTree ();
bstree->insertNode(1);
}
Inside BSTree::_insertNode, the root variable is a copy created on the stack. If you want to change what the root variable points, you'll have to pass by reference.
No, clearly root is a Node* as specified in the code.
The root that is a member of the class and the root that is a parameter to a member function are obviously different pointers, so they have different addresses. I suspect what you wanted was the address root holds (i.e. the address of the Node root points to.)
If that's the case: cout << "1) Address held by root: " << root << '\n';