【问题标题】:Problems with double pointers双指针的问题
【发布时间】:2012-11-16 01:49:30
【问题描述】:

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

【问题讨论】:

  • 为什么需要双指针?
  • 我使用双指针作为我的旋转和平衡方法的参数;这是一棵红黑二叉搜索树

标签: c++ pointers segmentation-fault


【解决方案1】:

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

【讨论】:

  • 为了澄清@jma127的回答,你只初始化了*temp,但还没有初始化temp
【解决方案2】:

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

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

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

【讨论】:

    【解决方案3】:

    看起来您不想在这里使用双指针(或者我更喜欢称它们为指向指针的指针)。 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 );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-13
      • 1970-01-01
      • 2011-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-19
      相关资源
      最近更新 更多