title: Code to add element to the beginning of a list in c - what's the error?
body: <p>I'm told that this will fail to correctly add the node to the list but I've tested it and it seems to work. Can anyone let me know what's incorrect in this code?</p>
  
  <pre><code>struct node {
     int num;
     struct node* next;
  };
  
  void add_first(struct node* head, struct node* new_node) {
     new_node-&gt;next = head;
     head = new_node;
  }
  </code></pre>
  
  <p>The exact question I'm trying to answer is:</p>
  
  <p>a) This function will fail to give the expected result (i.e., add the node). What is the problem and when does it occur?</p>
  
  <p>To try and find the issue, I've created four nodes, used the add_first function on them and then displayed the results. I seem to get correct output, though. Here's the program I wrote overall, not including the above functions:</p>
  
  <pre><code>void display(struct node* head) {
      printf("%d   ", head-&gt;num);
      if(head-&gt;next == NULL) {
          return;
      }
      display(head-&gt;next);
  }
  
  int main() {
      struct node* n1;
      struct node* n2;
      struct node* n3;
  
      n1 = (struct node*)malloc(sizeof(struct node*));
      n2 = (struct node*)malloc(sizeof(struct node*));
      n3 = (struct node*)malloc(sizeof(struct node*));
  
      n1-&gt;num = 1;
      n2-&gt;num = 2;
      n3-&gt;num = 3;
  
      add_first(n1, n2);
      add_first(n2, n3);
  
      display(n3);
  
      return 0;
  }
  </code></pre>
  
  <p>The output I'm getting is:</p>
  
  <blockquote>
    <p>3   2   1   </p>
  </blockquote>
  
  <p>Which seems to be correct. So, if I'm getting the correct output, why will the function fail to give the expected result? I don't see a problem in it.</p>