0

I was hoping someone could explain why my professor placed a double pointer in this sample code he gave us. head is declared as Node *head in main, so why did he pass it in as a double pointer? As far as I can tell it would work the exact same if I dropped the extra star and in the function dropped all the stars on head.

Thanks

void addLast(Node **head, int value)
{
  Node *temp; 
  temp = *head;
  Node *var = (Node *)malloc(sizeof (Node));
  var->data=value;
  if( *head==NULL)
  {
      *head=var;
      (*head)->next=NULL;
  }
  else
  {
      while(temp->next!=NULL)
      {     
           temp=temp->next;
      }
      var->next=NULL;
      temp->next=var;
  }
}
north.mister
  • 500
  • 1
  • 7
  • 24
  • 2
    `head` is an array of pointers to `Node` instead of an array of `Node`s. It would help to see what is actually being passed as argument for `head` – Paulo Bu Mar 20 '14 at 14:06
  • but when passed in a `Node **head` is it not a pointer to an array of pointers? – north.mister Mar 20 '14 at 14:08

1 Answers1

3

Arguments in C are pass-by-value - they are copied. If you were just to pass a single pointer, Node *, the head argument is a copy of the pointer which was passed in, meaning that any modifications to it would only be local to the function. This means the operation

head = var

would just overwrite the function's copy of the pointer rather than modifying the actual list (which lives outside the function). By passing a pointer to the head pointer (Node **), you allow modification of the external list through dereferencing the argument.

mtripp100
  • 231
  • 1
  • 5