为什么这个函数应该通过引用来调用?
Why this function should be called by reference?
我有一段这样的代码(实现树)
struct Node
{
int val;
struct node* left,*right;
Node(int x){
val=x;
left=right=NULL;
}
};
void insert(Node* &h,int val){
if(h==NULL){
h=new Node(val);
return;
}
if(h->val > val){
insert(h->left,val);
}
else {
insert(h->right,val);
}
}
void temp(Node* h,int val){ // Node* h doesn't seem to work but
// Node*& h does!!!
insert(h,val);
}
int main() {
struct Node* R=NULL;
for(int i=0;i<5;i++){
cin>>x;
temp(R,x);
}
return 0;
}
请忽略库的小错误和其他正式包含(此代码不用于编译)。
我的问题是 :- 为什么地址需要在提到的行中通过引用传递?
我的观点:我将 Root 的地址从主函数发送到临时函数,然后临时函数通过 参考将该地址发送到插入函数 插入正在永久更改它的函数,那么为什么不在此处更改根地址?如果这是一个错误,那么这里实际更改的地址是什么?
因为,否则参数会传值。因此,main 的 R
或树的根节点在 temp()
/insert()
returns.
之后将完全保持不变
如果一开始是NULL
,在temp()
returns之后还是NULL
,甚至,据说插入了一个新的节点作为根节点。发生的只是参数的值副本被更新,而不是真正的根节点,泄漏内存。
由于临时函数将 h 作为指针的引用,该程序将导致段错误。
将临时函数的签名更改为void temp(Node* &h, int val)
,它将起作用。
insert 函数为 h 分配内存,但 temp 函数将编译器内部创建的临时变量传递给 insert 函数
我有一段这样的代码(实现树)
struct Node
{
int val;
struct node* left,*right;
Node(int x){
val=x;
left=right=NULL;
}
};
void insert(Node* &h,int val){
if(h==NULL){
h=new Node(val);
return;
}
if(h->val > val){
insert(h->left,val);
}
else {
insert(h->right,val);
}
}
void temp(Node* h,int val){ // Node* h doesn't seem to work but
// Node*& h does!!!
insert(h,val);
}
int main() {
struct Node* R=NULL;
for(int i=0;i<5;i++){
cin>>x;
temp(R,x);
}
return 0;
}
请忽略库的小错误和其他正式包含(此代码不用于编译)。
我的问题是 :- 为什么地址需要在提到的行中通过引用传递?
我的观点:我将 Root 的地址从主函数发送到临时函数,然后临时函数通过 参考将该地址发送到插入函数 插入正在永久更改它的函数,那么为什么不在此处更改根地址?如果这是一个错误,那么这里实际更改的地址是什么?
因为,否则参数会传值。因此,main 的 R
或树的根节点在 temp()
/insert()
returns.
如果一开始是NULL
,在temp()
returns之后还是NULL
,甚至,据说插入了一个新的节点作为根节点。发生的只是参数的值副本被更新,而不是真正的根节点,泄漏内存。
由于临时函数将 h 作为指针的引用,该程序将导致段错误。
将临时函数的签名更改为void temp(Node* &h, int val)
,它将起作用。
insert 函数为 h 分配内存,但 temp 函数将编译器内部创建的临时变量传递给 insert 函数