在C++中复制链接列表时使用指针与地址运算符

sne*_*zle 0 c++ pointers linked-list singly-linked-list

我制作了以下链表结构和printList函数.两者都正常运行:

struct Node{
    int data;
    Node *np;
};

void printList(Node *x){
    cout << x->data << " ";
    if (x->np != NULL){
        printList(x->np);
    }
    return;
}
Run Code Online (Sandbox Code Playgroud)

然后我决定编写一个递归函数来复制链表.一个实现,返回指针值,工作...而另一个,返回一个地址 - 不起作用...我不能为我的生活弄清楚为什么会这样:

这有效:

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;
}
Run Code Online (Sandbox Code Playgroud)

这不起作用:

Node * copyList(Node *x){
    Node y = {x->data,NULL};
    if (x->np != NULL){
        y.np = copyList(x->np);
   }
   return &y;
}
Run Code Online (Sandbox Code Playgroud)

我有点困惑为什么.我会假设一个指针本质上是指一个内存地址,返回&y就好了......

小智 6

在第二种情况下,当函数调用结束时,您创建的Node y对象将超出范围.您返回的地址将无效.