Search code examples
cpointerspointer-to-pointer

Pointer-to-Pointer and linked list, passing parameters per value


Background is that I am experimenting with pointer-to-pointer in C by implementing a linked list. My question is regarding the difference in the two pieces of code and why the first one is giving expected output, but not the other one. Why does the first piece of code not advance head "outsite" the function which code 2 seems to do?

void add_node(int x, Node **head){
if(*head == NULL){
    Node *new_node = (Node*) malloc(sizeof(new_node));
    new_node->x = x;
    *head = new_node;
} else {
    Node *n = *head;

    while(n->next != NULL){
        n = n->next;
    }

    Node *new_node = (Node*) malloc(sizeof(new_node));
    new_node->x = x;
    n->next = new_node;
}
}

Output is as expected if I add 4 elements and after each addition print the list: 1 | 12 | 123 | 1234

void add_node(int x, Node **head){
if(*head == NULL){
    Node *new_node = (Node*) malloc(sizeof(new_node));
    new_node->x = x;
    *head = new_node;
} else {
    while((*head)->next != NULL){
        *head = (*head)->next;
    }

    Node *new_node = (Node*) malloc(sizeof(new_node));
    new_node->x = x;
    (*head)->next = new_node;
}
}

Output is following: 1 | 12 | 23 | 34


Solution

  • In the first example you are using the pointer n to travel the linked list, you're assigning it to n->next, which is exactly what you want to do to travel a linked list. In the second example, you are changing what the head pointer is pointing to:

    *head = (*head)->next;
    

    You're essentially moving the beginning of the linked list to another node, that's why you're having such behavior.