双指针问题 [英] Problems with double pointers

查看:54
本文介绍了双指针问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm getting a segmentation fault when I try to create a new Node object with the pointer variable *temp in line 15 below. I'm still pretty new to c++ and how double pointers work, especially when used in combination with &. Thanks for any help.

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 将失败,因为没有要取消引用的值.如果你真的需要一个指向指针的指针,你可以声明单指针并使用 & 运算符来获取双指针.

The variable temp is not initialized. Therefore, trying to dereference temp will fail, as there is no value to dereference. If you really need a pointer to a pointer, you could just declare the single pointer and use the & operator to get the double pointer.

这篇关于双指针问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆