简体   繁体   中英

In C++, are changes to pointers passed to a function reflected in the calling function?

If I pass a pointer P from function f1 to function f2, and modify the contents of P in f2, will these modifications be reflected in f1 automatically?

For example, if I need to delete the first node in a linked list:

void f2( Node *p)
{
    Node *tmp = p;
    p = p -> next;
    delete tmp;
}

Will the changes made to P be reflected in the calling function, or will it now point to a memory space that has been deallocated?

( My intuitive answer here is no, changes are not reflected. However, good sources tell me that the above code will work. Can someone take the time to give the answer and explain the reasoning behind it also please? Also, if the above code is faulty, how can we achieve this without using a return type? )

If I pass a pointer P from function f1 to function f2, and modify the contents of P in f2, will these modifications be reflected in f1 automatically?

No. Since C and C++ implement pass-by-value, the value of the pointer is copied when it's passed to the function. Only that local copy is modified, and the value is not copied back when the function is left (this would be copy-by-reference which a few languages support).

If you want the original value to be modified, you need to pass a reference to the pointer, ie change your signature of f2 to read:

void f2( Node*& p)

However , your f2 not only changes the pointer p , it also changes its underlying value (= the value being pointed to) by using delete . That change is indeed visible to the caller.

This will work, althrough not the way you want to.

If you call it like:

Node* mynode = new Node(); /*fill data*/
f2(mynode);

-> there will be the content of mynode undefined.

it will pass the value of the pointer to another function, and the value (p) will be local for function f2. If you want to modify it, use this way:

Node* mynode = new Node(); /*fill data*/
f2(&mynode);

void f2(Node** p)
{
 Node* tmp = *p;
 *p = (*p)->next;
 delete tmp;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM