【问题标题】:Why pointer argv is not updating?为什么指针 argv 没有更新?
【发布时间】:2018-01-13 04:07:22
【问题描述】:

有人能帮我理解为什么在 new() 调用后指针头没有更新吗?

expected: val:0 # call new(), 更新 l0.val 为 0 实际: val:253784 # 为什么更新 l0.val 不是通过指针更新

https://www.edaplayground.com/x/54Nz

#include <stdio.h>
#include <stdlib.h>

typedef struct _node {
  int val;
  struct _node *next;
} node;

//construct the struct
void new(node *head) {
  //malloc return a pointer, type casting to (node*)
  node *head_l = (node*)malloc(sizeof(node));

  if(!head_l) {
    printf("Create Fail!\n"); 
    exit(1); 
  }

  head_l->val = 0;
  head_l->next = NULL;

  printf("head_l->val:%0d\n",head_l->val);

  //why head = head_l doesn't work??
  head = head_l;
  //The line below works
  //*head = *head_l;
}

int main() {
  node l0;
  new(&l0);
  printf("val:%0d\n",l0.val);
}

【问题讨论】:

  • 你能详细说明一下吗?如果改成*(l0.val),会导致编译错误。

标签: pass-by-pointer


【解决方案1】:

函数参数只接收它们被传递的值,而不是对参数的任何引用或其他连接。调用该函数时,参数head 设置为指向l0 的指针的值。更改 head 不会更改 l0

【讨论】:

  • 感谢您的解释,埃里克。 “参数head设置为指向l0的指针的值。改变head不会改变l0。”,有点抽象,你能详细说明一下吗?我是使用指针的初学者。谢谢,汤姆
  • 我花了一些时间,终于明白 Eric 想说什么了。
【解决方案2】:

通过参考帖子-Having a function change the value a pointer represents in C,我能够找到根本原因。

假设 head 的地址是 [0x0000_0010] -> 具有 NULL 的节点对象。

head_l 的地址是 [0x0003_DF58] -> node.val=0 的节点对象。

头=头_l;仅将 head 从 0x0000_0010 修改为 0x0003_DF58。

*head = *head_l;将 [0x0000_0010] - head points 的值修改为 [0x0003_DF58] - head_l points 的值。

后者会将目标值(NULL)更改为新值(node.val=0)。

【讨论】:

    猜你喜欢
    • 2021-09-29
    • 2011-01-19
    • 2020-04-22
    • 2011-02-08
    • 1970-01-01
    • 2021-09-17
    • 2019-08-25
    • 2022-07-16
    相关资源
    最近更新 更多