Reputation: 402
I do not understand what is wrong with the following piece of code. I am trying to create a linked list in C. I am creating a typedef struct which I call a person, then I declare a pointer that points to that structure and I am trying to allocate some memory for it to be able to store all its components. The compiler gives back an error saying that 'head' does not name a type.
typedef struct node {
int num;
struct node *next;
} person;
person *head = NULL;
head = (person*)malloc(sizeof(node));
Upvotes: 0
Views: 350
Reputation: 2093
Assuming the assignment to head is in a function, it is still incorrect as node
is not a valid type or variable. It's either struct node
but as you typedef
'd that you should use person
head = malloc(sizeof(person));
But as the variable head
is already of type person*
you can also do
head = malloc(sizeof(*head));
which has the advantage you no longer need to know the exact type name (should you ever change it)
Also note that casting the result of malloc
is not needed and unwanted.
You will have to check for the result being NULL though.
Upvotes: 1