双指针问题

Problems with double pointers

本文关键字:问题 指针      更新时间:2023-10-16

当我尝试使用下面第 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;

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

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

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

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

看起来你不想在这里使用双指针(或者我更喜欢称呼它们的指针到指针)。 temp保存一个永远不会初始化的指针的地址。 因此,当您尝试创建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 );