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

被刻印的时光 ゝ 提交于 2019-12-08 00:51:30

问题


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? )


回答1:


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, i.e. 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.




回答2:


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;
}


来源:https://stackoverflow.com/questions/3708383/in-c-are-changes-to-pointers-passed-to-a-function-reflected-in-the-calling-fu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!