【问题标题】:Different ways to pass pointers to functions as arguments [duplicate]将指向函数的指针作为参数传递的不同方法[重复]
【发布时间】:2020-12-12 10:02:33
【问题描述】:

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

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?

【问题讨论】:

  • 你需要学习指针。我们无法取代一本好的 C 书。阅读它,做所有的练习,你最终会明白其中的区别。
  • 我其实是自己写的问题就明白了,我真正不明白的只是最后一个例子,但是通过写问题我明白了。
  • 在第一个上,我确切地知道我只是感到困惑的区别。区别只是通过值或引用传递。无论如何,我没有兴趣说服你。美好的一天。

标签: c pointers linked-list


【解决方案1】:

当你想对列表进行更改时,你必须传递节点 *a,通过传递指向列表的指针,函数将更改原始列表的内存地址。在第一种情况下,函数接收指向节点的指针。您初始化了一个节点(节点 a),因此如果您想传递一个指向结构的指针,您必须使用 & (&a) 传递指向节点 a 的地址。在第二种情况下,函数接收到指向节点的指针(双指针),并且您初始化了指向结构(不是结构)的指针,因此您只需要使用 & 来获取双指针。

【讨论】:

    【解决方案2】:

    用以下几行和相应的 cmets 可视化它:

    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" 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-16
      • 2019-08-17
      • 2013-11-18
      • 2010-11-19
      • 2020-03-07
      • 1970-01-01
      • 2014-04-16
      • 2013-08-11
      相关资源
      最近更新 更多