how can there be another 'struct node* next' inside struct node?
struct node *
is a pointer to struct node
user-defined data type. You can call it pointer to itself
. A struct can have pointers to itself or other structs as members.
The C for Programmers a Deitel book
says:
A structure cannot contain an instance of itself. For example, a
variable of type struct employee cannot be declared in the definition
for struct employee. A pointer to struct employee, however, may be
included.
To read more on why a struct can't contain an instance of itself, you can go through this link.
typedef is just a way to save characters instead of typing 'struct node' every time, which we can do by typing 'test' in this case.
Without the forward declaration the struct name is still valid inside the struct definition (i.e. you can used struct A), but the typedef is not available until after the typedef definition is complete. You can read more over here.
I thought structs had to have structure members, so what does 'struct node* next' accomplish in this code? 'struct node* next' has no structure members, so what is the point of writing struct?
You can access the members of pointer to struct node by using ->
operator. Consider a small linked link program:
test a;
test b;
a.data = 5;
b.data = 10;
b.next = NULL;
a.next = &b; // A linked list has been formed.
printf("Data of first node is %d and second node is %d\r\n", a.data, a.next->data); // It will print "Data of first node is 5 and second node is 10"