简体   繁体   English

typedef struct 声明返回错误

[英]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.我正在尝试在 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.我正在创建一个我称之为人的 typedef 结构,然后我声明一个指向该结构的指针,并且我试图分配一些 memory 以便它能够存储其所有组件。 The compiler gives back an error saying that 'head' does not name a type.编译器返回一个错误,说 'head' 没有命名类型。

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.假设对 head 的分配在 function 中,它仍然不正确,因为node不是有效的类型或变量。 It's either struct node but as you typedef 'd that you should use person它是struct node但当你typedef 'd 你应该使用person

head = malloc(sizeof(person));

But as the variable head is already of type person* you can also do但是由于变量head已经是person*类型,您也可以这样做

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.另请注意,不需要也不需要转换malloc的结果。

You will have to check for the result being NULL though.不过,您必须检查结果是否为 NULL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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