Answer: Because it is convenient. It allows a function to manipulate a pointer, regardless of where it is stored.
The fact is that with a linked list you want to save the pointer to the first node somewhere. This pointer is not part of struct _node . But you can pass your address to the function in the same way as the address of any next_node pointer in any node that is in the list. That is, you do not need to specifically handle the case with an empty list.
As an example:
void pushFront(node* list, int value) { node newNode = malloc(sizeof(*newNode)); newNode->contents = value; newNode->next_node = *list; *list = newNode; }
I can call this function as follows:
int main() { node myList = NULL; pushFront(&myList, 42); printf("The answer is %d!\n", myList->contents); }
Note that this code works even when myList initialized to NULL ! Similar elegant code arises when going through a list, inserting or deleting nodes along a path.
Also: I think this is a bad habit of typedef pointer types: it hides the fact that a thing is a pointer. I would very much prefer the following definitions:
typedef struct node node;
This implies a change in the implementations of the functions to the following (only three stars):
void pushFront(node** list, int value) { node* newNode = malloc(sizeof(*newNode)); newNode->contents = value; newNode->next_node = *list; *list = newNode; } int main() { node* myList = NULL; pushFront(&myList, 42); printf("The answer is %d!\n", myList->contents); }
You see, when I see a line like
node newNode = malloc(sizeof(*newNode));
I immediately have a WTF moment: "Why is newNode considered as a pointer when it is just ... oh wait, this is really a type of pointer! Someone must really clear this code!" On the other hand, when I see
node* newNode = malloc(sizeof(*newNode));
everything is clear right away: newNode is a pointer that malloc() stands out in a standard way.
The fact is that I do not expect a pointer if I do not see the type * in the type. Typed pointer types violate this assumption, which leads to poor readability of the code. Especially C programmers, like their code, are clearly in places like this.
Of course, you should adhere to the recommendations that your teacher gives, but be sure to change the pointer-typedef-habit as soon as you can.