Pointer Question

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?

Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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);
}
Last edited on
By the way, when I print the address of root as the following,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
BSTree::BSTree () {
    root = NULL; // root is a private variable of type Node*.
}

// public function
void BSTree::insertNode (int v) {
    cout << "1) Address of root: " << &root << '\n';
    // This does not insert a new node. Why?
    _insertNode(root, new Node (v));
}

// private function
void BSTree::_insertNode (Node* root, Node* node) {
    cout << "2) Address of root: " << &root << '\n';
    if (root == NULL) {
        root = node;
    } else {
        if (node->value < root->value) {
            _insertNode(root->left, node);
        } else {
            _insertNode(root->right, node);
        }
    }
}


I get this. They should be the same. How did this happen?

1
2
1) Address of root: 0x89b1008
2) Address of root: 0xbfb46a34
Last edited on
The problem is:
 
root = node;


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.
Thank you.

I did not know C++ has this thing called reference. I guess I have some homework to do.
The problem is:
root = node;


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';
Topic archived. No new replies allowed.