Why do we have *head after the curly bracket? How would head be used later in the program?
- Because it's bad style and it's declaring a global variable of type
struct node * named head.
Also, why is it valid to use a struct inside itself? I think it should be defined first before being used.
- You can always declare pointers to incomplete types, and then at compile time when dereferencing the pointer, the definition must be available, this wouldn't work for example
This is from the c standard draft 1570, §6.7.2.1
- A structure or union shall not contain a member with incomplete or function type (hence, a structure shall not contain an instance of itself, but may contain a pointer to an instance of itself), except that the last member of a structure with more than one named member may have incomplete array type; such a structure (and any union containing, possibly recursively, a member that is such a structure) shall not be a member of a structure or an element of an array.
I've highlighted the relevant parts. So it means that it can be a pointer, but not an instance of itself, an example of the meaning of the qoute
struct node {
int data;
struct node next;
} *head;
would be invalid because the type struct node is not defined, but this would do it
struct node *head;
struct node {
int data;
struct node *next;
};
and it's equivalent to the original code.
This feature is what makes the wonderful linked lists possible, because since next is a pointer to a struct node then you can link current node, to another node of the same type and so on, it's normally done such that last node, is linked to a special value, NULL, this would be a very simple example
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct node {
int data;
struct node *next;
};
int main(int argc, char **argv)
{
struct node *head;
struct node *next;
struct node *current;
head = malloc(sizeof(*head));
if (head != NULL)
{
head->data = 1;
head->next = NULL;
}
next = malloc(sizeof(*next));
if (next != NULL)
{
next->data = 2;
head->next = next;
next->next = NULL;
}
for (current = head ; current != NULL ; current = current->next)
fprintf(stderr, "node@%p: %d\n", current, current->data);
free(next);
free(head);
return 0;
}
a more sophisticated program would have a function to create/append/prepend nodes from the list.
*headis a variable,pointer of typestruct nodestruct nodeonce the{is reached for the embedded reference to be OK. (I just happened to be looking at an answer of mine where that section was quoted, mainly for the material in the '...' which I've left out here.)