0

I have a linked list implemented in C as so:

struct node {
    int value;
    struct node* next;
}; 
typedef struct node node_t;


node_t* new_node(int value){
    
    node_t* n = malloc(sizeof(node_t));
    n->value = value;
    n->next = NULL;
    
    return n;
    
}

Why does this work:

node_t* insert_at_head(node_t **head, node_t *node_to_insert){
    
    node_to_insert->next = *head;
    
    *head = node_to_insert;
    
    return node_to_insert;
} 

but this doesn't?:

node_t* insert_at_head(node_t *head, node_t *node_to_insert){

    node_to_insert->next = head;
    
    head = node_to_insert; 
    
    return node_to_insert; 
}

This is how it is implemented in main:

    node_t* head = NULL;
    node_t* tmp;
    
    for(int i = 0; i < 25; i++){
        
        tmp = new_node(i);
        
        insert_at_head(&head, tmp); // call to working function
        insert_at_head(head, tmp); // call to not working version of function
        
    }

i.e Why do I need to use a pointer to a pointer?

Thank you for your time

For reference I'm using this tutorial: (~12m mark)
https://www.youtube.com/watch?v=VOpjAHCee7c&t=735s
Excellent so far, this is just a gap in my understanding as I'm new to C, not a fault of the video.

  • Because arguments are *copies* of what are passed. – MikeCAT Mar 02 '21 at 12:49
  • To fix the non-working one, you need to update `main`'s `head` variable: `head = insert_at_head(head, tmp);` or `insert_at_head(head, tmp); head = tmp;`. (The return value of the version of `insert_at_head` with the double pointer probably isn't very useful, so it could be changed to use a return type of `void`.) – Ian Abbott Mar 02 '21 at 13:05
  • Thank you! Would it be accurate to say this?: **head in signature is saying 'parameter 'head' is a pointer, to the pointer 'head', which points to our list head.' *head in the method is saying 'access the thing parameter 'head' points to - which is the pointer to our list head.' – Billy Smith Mar 02 '21 at 17:29

0 Answers0