In C, if you want the function to be able to change the value obtained in its arguments, you need to pass the address of that value. So, to change the value of the list pointer, you need to pass the address of the list pointer. Your addFirst () function should look like this:
void addFirst(struct node **list, int value){ struct node *new_node = (struct node*) malloc (sizeof (struct node)); new_node->value = value; new_node->next = *list; *list = new_node; }
And when you call this function, you call it like this:
addFirst(&list, value);
Now, if you want to keep the signature of the function, it is possible to change the way you consider the head of the node. If you state that your node head is only designed to hold a pointer to the first value, but does not contain a value in itself, you can do something like this:
struct node *head; void addFirst(struct node *list, int value){ struct node *new_node = (struct node*) malloc (sizeof (struct node)); new_node->value = value; new_node->next = list->next; list->next = new_node; } addFirst(head, 45);
Now you have only all your functions that work in the list so that they change, so they work the same way, assuming that the "head" points only to the real first node of the list, but the list itself is not a member. A "real" head, for all practical purposes, head-> next.
source share