Search code examples
cpointerslinked-listinsertion

What's the point of using pointer to pointer?


I found this code on a website for inserting a node in a linked list at the beginning of the list.

void push(struct Node** head_ref, int new_data)
{
/* 1. allocate node */
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));

/* 2. put in the data  */
new_node->data  = new_data;

/* 3. Make next of new node as head */
new_node->next = (*head_ref);

/* 4. move the head to point to the new node */
(*head_ref)    = new_node;
}

This is the function call-

push(&head, 7);

My question is why go the long way by passing the address of a pointer and then subsequently extracting the value at the address inside the function. Why can't we simply pass the pointer head in the function and later make the assignment like -

new_node->next=head_ref;

?


Solution

  • If you passed head and not &head, the line

    (*head_ref)    = new_node;
    

    will have to be changed to

    head_ref    = new_node;
    

    However, it will be a local change in the function. It won't change the value of head in the calling function. There are two problems with that:

    1. The calling function will never get a working list.
    2. The memory allocated in the function will be a memory leak.