2014-01-26 45 views
-1

我不知道爲什麼運行下面的代碼時,我的指針不更新:BST路過指針更新

void bst_insert(Node* root, int data) { 

    if (root == NULL) { 
    Node* n = new Node(); 
    n->data = data; 
    n->right = NULL; 
    n->left = NULL; 
    root = n; 
    cout << root->data << endl; 
    return; 
    } 

主營:

int main() { 

    Node* root = NULL; 
    bst_insert(root, 5); 
    cout << root << endl 
} 

我希望根主要指向然而它的new Node仍然NULL。爲什麼?

+0

將指針的值複製到新變量中。然後你改變那個變量的值。新的價值不會在功能外面看到。 – pmr

回答

4

因爲您正在通過值傳遞指針,所以您正在更改bst_insert中的本地指針。改爲傳遞指針的引用:

void bst_insert(Node*& root, int data) 
        ^
+0

我覺得很愚蠢。謝謝。 –