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);
}
Tom Ma
  • 1
  • 4

2 Answers2

0

Function parameters receive only the value they are passed, not any reference or other connection to the argument. When the function is called, the parameter head is set to the value of a pointer to l0. Changing head does not change l0.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
  • Thanks for your explaination, Eric. "the parameter head is set to the value of a pointer to l0. Changing head does not change l0.", is a little bit abstract, can you elaborate a little bit? I am a beginner on using pointer. Thanks, Tom – Tom Ma Jan 13 '18 at 05:10
  • I spent some time, and finally understood what Eric was trying to say. – Tom Ma Jan 13 '18 at 23:41
0

By referring to the post - Having a function change the value a pointer represents in C, I am able to find the root cause.

Let's say Address of head is [0x0000_0010] -> node object with NULL.

Address of head_l is [0x0003_DF58] -> node object with node.val=0.

head = head_l; only modify head from 0x0000_0010 to 0x0003_DF58.

*head = *head_l; modify [0x0000_0010] - the value of head points, to [0x0003_DF58] - the value of head_l points.

The latter one will change the destination value(NULL) to new value(node.val=0).

Tom Ma
  • 1
  • 4