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

这一生的挚爱 提交于 2019-12-06 05:40:00

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.

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