首页 > 解决方案 > 将指向函数的指针作为参数传递的不同方法

问题描述

我不明白为什么当我调用这样的函数时:

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而不是node a在处理链表的头部时?

标签: cpointerslinked-list

解决方案


使用以下行和相应的注释将其可视化:

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" 

推荐阅读