3

当我尝试使用下面第 15 行中的指针变量 *temp 创建一个新的 Node 对象时,我遇到了分段错误。我对 c++ 以及双指针的工作方式仍然很陌生,尤其是与 & 结合使用时。谢谢你的帮助。

void bst::insert(int n) {
    Node **temp;
    Node *r, *parent;
    // Tree is empty
    if (root == NULL) {
        root = new Node;
        root->parent = NULL;
        root->value = n;
        root->left = NULL;
        root->right = NULL;
        root->isBlack = true;
    } else {
        r = root;
        // Create a node with the given value, n
        (*temp) = new Node;
        (*temp)->value = n;
        (*temp)->left = NULL;
        (*temp)->right = NULL;
        (*temp)->isBlack = false;
4

3 回答 3

5

变量temp未初始化。因此,尝试取消引用temp将失败,因为取消引用没有任何价值。如果你真的需要一个指向指针的指针,你可以只声明单指针并使用&运算符来获取双指针。

于 2012-11-16T01:51:51.310 回答
2

temp没有指向任何有效的东西,所以当你这样做时

(*temp) = new Node;
(*temp)->value = n;
(*temp)->left = NULL;
(*temp)->right = NULL;
(*temp)->isBlack = false;

else您的 -statement 的分支中,当您取消引用指针变量if时,您将调用未定义的行为。temp

于 2012-11-16T01:52:14.937 回答
1

看起来您不想在这里使用双指针(或者我更喜欢称它们为指向指针的指针)。 temp保存一个从未初始化过的指针的地址。因此,当您尝试创建 a 时,您会尝试使用已初始化new Node的任何随机数据来创建它。temp

你可以只使用一个普通的指针,然后如果你以后需要使它成为一个指向指针的指针,只需使用&temp

Node * temp;

// <snip>

temp = new Node;
Node->value = n;
//  etc.

SomeFunc( &temp );  //  temp will be passed as a pointer-to-pointer (Node**).

或者,如果您坚持 temp 仍然是指向指针的指针,您可以使用:

Node * temp2 = new Node;  // Creates a new Node and assigns the address to temp2
temp = &temp2;            // Assigns the address of the pointer to the Node (temp2) to temp.

//  Now do stuff.

请记住,您需要像这样删除它:

delete( *temp );
于 2012-11-16T12:20:00.020 回答