TutenStain
TutenStain

Reputation: 247

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

Upvotes: 0

Views: 54

Answers (2)

hit
hit

Reputation: 36

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.

Upvotes: 2

Naman
Naman

Reputation: 31888

Evaluate input 1,2,3 and focus on the head.

while((*head)->next != NULL){
    *head = (*head)->next;
}
Node *new_node = (Node*) malloc(sizeof(new_node));
        new_node->x = x;
        (*head)->next = new_node;

leaves the head pointing somewhere, which your output is depicting ;)

For input 1 and 1,2 the conditions are not met and you escape.

Upvotes: 0

Related Questions