【发布时间】: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