双指针问题
Problems with double pointers
当我尝试使用下面第 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 );
相关文章:
- 关于 c++ 函数中指针赋值的简单问题
- 链表指针问题
- C++ 关于指针取消引用的技术问题
- C++中的指针和常量问题不大
- 包含矢量指针的结构的内存释放问题
- 指针问题:从不兼容的类型"int"分配给"int *"
- 将字节数组转换为带有字节序问题的指针
- 关于如何使用指向主窗口的指针的 QT 问题
- 当成员值从指针更改为非指针时,C++常量问题
- 为什么循环会导致指针出现问题?
- 使用指针计算堆栈问题的大 O 表示法
- 构造函数 (C++) 中的 char 指针参数存在问题
- 指向包含对齐 C 结构C++类的 C 指针的对齐问题
- 涉及指针和手动实现的矩阵类的问题
- 从基指针到派生的强制转换问题
- 迭代器的指针操作问题
- 64 位迁移问题:指针更改
- C++模板使用问题指针
- 跳到C++第13章练习问题4-指针
- 用std::pair数组初始化std::map问题(指针错误?)