I am studying code examples from my professor in order to become better acquainted with linked data structures.
In our linked-list.c example the professor defines a
Does it have something to do with the fact that if you don't include a lower case
node
then when the compiler is evaluating the code it will not be able to understand what is meant by "struct node *next
"?
Yes.
The node
in struct node
is the tag of the struct type. If you give the struct a tag, you can refer to that type from the moment on the tag is complete, so in
typedef struct node {
int data;
struct node *next;
} Node;
the struct node *next;
declares a member next
that is a pointer to the struct type being defined. The typedef name Node
is not available before the ;
ending the definition is reached.
If you omit the tag, you cannot refer to the type being defined in any way before the typedef
is complete, so in
typedef struct {
int data;
struct node *next;
} Node;
the line struct node *next;
declares a new, unrelated, incomplete struct
type with the tag node
that next
points to.
That's valid, but nothing about struct node
is known (unless it is defined somewhere else), so you can't use the next
pointer without casting it to a pointer to a complete type everywhere (not quite everywhere, Node foo; foo.next = malloc(12);
etc. would still work).