0

Can somebody help me understand why the pointer head is not updated after new() call?

expected: val:0 # call new(), update l0.val to 0 actual: val:253784 # why update l0.val not update by the pointer

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);
}
4

2 回答 2

0

通过参考帖子-让函数更改指针在 C 中表示的值,我能够找到根本原因。

假设头部地址是 [0x0000_0010] -> 节点对象为 NULL。

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

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

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

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

于 2018-01-13T23:55:00.463 回答
0

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

于 2018-01-13T04:25:48.357 回答