Search code examples
cfunctionpointersstructpointer-to-pointer

Why is a pointer to a structure not overridable in a function?


lets look at this code:

typedef struct nodes{
    int val;
    struct nodes next;
} node;

insertHead(node *list, int val) {
    node *temp = malloc(sizeof(node));
    temp->val;
    temp->next = list;
    list = temp;
}

int main() {
    node *list = NULL;
    insert(list, 5);
}

Here if I try to call the list->val it does not work as if it passes in the copy of the list and did not actually set the new head of the list.

typedef struct nodes{
    int val;
    struct nodes next;
} node;

insertHead(node **list, int val) {
    node *temp = malloc(sizeof(node));
    temp->val;
    temp->next = *list;
    *list = temp;
}

int main() {
    node *list = NULL;
    insert(&list, 5);
}

I know that this will work, but my actual question is why doesn't the first example work. I mean I pass in the list into the function and list is a pointer to a structure. I'm new to C but isn't it correct to pass in the address of a structure to change its members and maybe override it. I totally understand that this would not work if I would pass in the struct itself with *list because it would just create a copy. but the node *list isn't a copy, it is a pointer to the actual structure, so why do I need to do this with a pointer-to-pointer-to-structure?

P.S: I'm new to C so don't judge too hard. This will be a linked list btw.


Solution

  • Because you want to modify the pointer itself, not the referenced value. To modify it you need to pass pointer to this pointer

    Similar to "normal" types. If you pass the integer, you cant modify it in the function. To archive that you need to pass pointer.