编辑指针指向函数内的位置 [英] Edit where a pointer points within a function

查看:122
本文介绍了编辑指针指向函数内的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个指向C ++中struct对象的指针。

I have a pointer to a struct object in C++.

 node *d=head;

我想通过引用将指针传递给函数,并编辑它指向的位置。我可以传递它,但它不会改变初始指针指向的位置,而只是在函数中的本地指针。函数的参数必须是指针正确吗?

I want to pass that pointer into a function by reference and edit where it points. I can pass it but it doesn't change where the initial pointer points but only the local pointer in the function. The arguments of the function must be a pointer right? And after how do I change it to show to a different object of the same struct?

推荐答案

你有两个基本的选择:Pass或通过 引用。传递指针需要使用指针指针:

You have two basic choices: Pass by pointer or pass by reference. Passing by pointer requires using a pointer to a pointer:

void modify_pointer(node **p) {
    *p = new_value;
}

modify_pointer(&d);

通过引用传递使用&

void modify_pointer(node *&p) {
    p = new_value;
}

modify_pointer(d);

如果您将指针传递为 node * d ,则修改函数中的 d 将只修改本地副本,如您所观察到的。

If you pass the pointer as just node *d, then modifying d within the function will only modify the local copy, as you observed.

这篇关于编辑指针指向函数内的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆