I made the following linked list structure and printList function. Both functioned correctly:
struct Node{
int data;
Node *np;
};
void printList(Node *x){
cout << x->data << " ";
if (x->np != NULL){
printList(x->np);
}
return;
}
Then I decided to write a recursive function to copy over a linked list. One implementation, returning a pointer value, works...whereas the other, returning an address-of didn't work...I can't for the life of me figure out why this is the case:
This works:
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;
}
This doesn't work:
Node * copyList(Node *x){
Node y = {x->data,NULL};
if (x->np != NULL){
y.np = copyList(x->np);
}
return &y;
}
I'm a little confused as to why. I would assume that given that a pointer essentially refers to a memory address, returning &y would be just as fine...
In the second case the Node y object you are creating will go out of scope when the function call will end. The address you are returning will then be not valid.