【发布时间】:2015-06-23 21:39:30
【问题描述】:
我做了如下链表结构和printList函数。两者都正常运行:
struct Node{
int data;
Node *np;
};
void printList(Node *x){
cout << x->data << " ";
if (x->np != NULL){
printList(x->np);
}
return;
}
然后我决定编写一个递归函数来复制一个链表。一种实现,返回一个指针值,工作......而另一种,返回一个地址不起作用......我一生都无法弄清楚为什么会这样:
这行得通:
Node * copyList(Node *x){
Node * y = new Node;
y->data = x->data;
if (x->np != NULL){
y->np = copyList(x->np);
}else{
y->np = NULL;
}
return y;
}
这不起作用:
Node * copyList(Node *x){
Node y = {x->data,NULL};
if (x->np != NULL){
y.np = copyList(x->np);
}
return &y;
}
我有点困惑为什么。我假设鉴于指针本质上是指内存地址,返回 &y 就可以了...
【问题讨论】:
-
取决于您的编译器,如果您打开警告,它应该能够准确地告诉您为什么这不起作用。
标签: c++ pointers linked-list singly-linked-list