简体   繁体   中英

typedef struct declaration gives back an error

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));

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM