Muc*_*ida 5 c++ pointers pass-by-reference dev-c++ visual-studio-2012
我正在创建一个在二叉树中插入元素的函数,首先,我在Visual Studio 2012上执行了以下操作:
void Insert(Nodo *root, int x){
if(root == NULL){
Nodo *n = new Nodo();
n->value = x
root = n;
return;
}
else{
if(root->value > x)
Insert(&(root)->left, x);
else
Insert(&(root)->right, x);
}
}
Run Code Online (Sandbox Code Playgroud)
但是这个相同的代码在Dev-C++中不起作用,我需要使用指针指针使其工作,如下所示:
void Insert(Nodo **root, int x){
if(*root == NULL){
Nodo *n = new Nodo();
n->value = x
*root = n;
return;
}
else{
if((*root)->value > x)
Insert(&(*root)->left, x);
else
Insert(&(*root)->right, x);
}
}
Run Code Online (Sandbox Code Playgroud)
有人知道它为什么会发生吗?
第一个代码不应编译。事实上它不能在 MSVC 2013 下编译。
为什么 ?
你的节点结构应该是这样的:
struct Nodo {
int value;
Nodo*left, *right; // pointer to the children nodes
};
Run Code Online (Sandbox Code Playgroud)
这意味着它(root)->left属于 类型Nodo*。因此,&(root)->left它的类型Nodo**与参数不兼容Nodo*。
不管怎样,在你的插入函数中,你肯定想改变树。但是,如果您这样做: root = n;您只需更新根参数(指针)。一旦您离开该功能,此更新就会丢失。在这里,您当然想要更改根节点的内容或更可能更改指向根节点的指针。
在第二个版本中,您将指向节点的指针的地址作为参数传递,然后在必要时更新该指针(预期行为)。
评论
如果您想通过引用进行传递,则可以“保存”第一个版本:
void Insert(Nodo * &root, int x){ // root then refers to the original pointer
if(root == NULL){ // if the original poitner is null...
Nodo *n = new Nodo();
n->value = x
root = n; // the orginal pointer would be changed via the reference
return;
}
else{
if(root->value > x)
Insert(root->left, x); // argument is the pointer that could be updated
else
Insert(root->right, x);
}
}
Run Code Online (Sandbox Code Playgroud)