首页 > 解决方案 > 为什么指针在 C++ 中丢弃值?

问题描述

这是一个简单的二叉搜索树(BST),我用它来说明我的问题

struct BST {
    int key;
    BST *left, *right;
};

这是一个将节点插入 BST的函数:

bool insert (BST *root, BST *node) {
    // base case. Do the insertion 
    if (root == nullptr) {
        root = node;
        return true;
    }
    if (root->key < node->key)
        insert(root->left, node);
    else
        insert(root->right, node);
}

这是我的主要内容:

int main () {
    // Make a root for the BST
    BST root = {10, nullptr, nullptr};
    BST *root_p = &root;

    // Insert node into BST
    BST node = {5, nullptr, nullptr};
    BST *node_p = &node;
    insert(root_p, node_p);

    // Should see the address of the inserted node
    cout << root_p->left << endl;  // it outputs 0 (nullptr). Why?

}

我正在尝试在 BST 上进行插入。我首先初始化了根,然后是一个指向根的指针,称为root_p. BST 中的任何插入都将从root_p. 然后我尝试在 BST 中插入一个新节点。

理想情况下,insert(root_p, node_p)应该导致root_p' 左指针的值node_p(遵循 BST 约定,其中左孩子的键较小)。然而,这并没有发生,而是root_p左指针仍然是一个空指针。为什么呢?任何帮助表示赞赏!

PS:我尝试将 insert 更改为对指针进行引用(即BST *&root),但这会产生相同的结果。

标签: c++c++11pointersbinary-search-tree

解决方案


推荐阅读