如何解决将指针传递给函数作为参数的不同方法
我不明白为什么我调用这样的函数:
graph
我必须作为参数typedef struct str_node{
int data;
struct str_node *next;
}node;
void begin(node *num);
int main(){
node a;
begin(&a);
传递,而我不能简单地通过&a
传递。确实,当我遇到这种情况时:
a
我必须通过void begin(node *head);
int main(){
node *a;
begin(a);
,而不是a
。但是当我遇到这种情况时:
&a
我必须再次通过void begin(node **head);
int main(){
node *a;
begin(&a);
,而不是&a
。此外,为什么在处理链接列表的标题时总是必须使用a
而不是node *a
?
解决方法
使用以下几行和相应的注释对其进行可视化:
int a = 5; // say,the compiler allocated 0xABCD0000 memory address for "a"
int *b = &a; // say,the compiler allocated 0xDCBA0000 memory address for "b"
// memory layout so far;
// variable memory address value
// a 0xABCD0000 5
// b 0xDCBA0000 0xABCD0000
foo(a); // pass the value of "a",which is "5".
// possible foo function decoration:
// foo(int x) {}
bar(&a); // pass the memory address of "a",which is "0xABCD0000"
// possible bar function decoration:
// bar(int *x) {}
baz(b); // pass the value of "b",which is,in turn,the memory address of "a"
// possible baz function decoration:
// baz(int *x) {}
boo(&b); // pass the memory address of "b",which is "0xDCBA0000"
// possible boo function decoration:
// boo(int **x) {}
// you'll need the last one,if you want to change the address the pointer is pointing at in the sub-function "boo"
,
要更改列表时,必须传递节点* a,通过将指针传递到列表,该函数将在原始列表的内存地址中进行更改。在第一种情况下,函数接收指向节点的指针。您初始化了一个节点(节点a),因此,如果要传递指向结构的指针,则必须使用&(&a)传递指向节点a的地址。在第二种情况下,该函数接收到一个指向节点的指针(双指针),并且您初始化了一个指向结构(而不是结构)的指针,因此您只需要使用&即可获得一个双指针。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。