struct声明中需要typedef

我正在尝试创建一个struct元素数组,如下所示:

#include  #include  struct termstr{ double coeff; double exp; }; int main(){ termstr* lptr = malloc(sizeof(termstr)*5); return 0; } 

当我编译它时,我得到如下错误:

 term.c: In function 'main': term.c:11:1: error: unknown type name 'termstr' term.c:11:31: error: 'termstr' undeclared (first use in this function) 

但是,当我将我的代码更改为以下内容时,它会照常编译:

 #include  #include  typedef struct termstr{ double coeff; double exp; }term; int main(){ term* lptr = malloc(sizeof(term)*5); return 0; } 

我添加了typedef(类型名称为term),将struct的名称更改为termstr,并使用term *作为指针类型分配内存。

这种情况是否始终需要typedef,即创建结构数组? 如果没有,为什么第一个代码会出错? 是否还需要typedef来创建和使用结构的单个实例?

第一种类型无效,因为您在termstr之前忘记了struct关键字。 您的数据类型是struct termstr但不仅仅是termstr 。 当您struct termstr ,结果名称将用作struct termstr的别名。

即使你不需要这样做。 使用typedef更好:

顺便一点也不要忘记释放内存:

阅读为什么要使用typedef?

您的工作代码应该是:

 #include  #include  struct termstr{ double coeff; double exp; }; int main(){ struct termstr* lptr = malloc(sizeof(struct termstr)*5); free(lptr); return 0; } 

它应该是:

 struct termstr * lptr = malloc(sizeof(struct termstr)*5); 

甚至更好:

 struct termstr * lptr = malloc(sizeof(*lptr)*5); 

在C中,数据类型的名称是“struct termstr”,而不仅仅是“termstr”。

你可以这样做:

 typedef struct termstr{ double coeff; double exp; } termstrStruct; 

然后你只能使用termstrStruct作为结构的名称:

 termstrStruct* lptr = malloc(sizeof(termstrStruct)*5); 

它并不总是必需的,你可以简单地编写struct termstr

别忘了free分配的内存!

Typedef是缩短这个的便捷方法:

 struct termstr* lptr = (struct termstr*)malloc(sizeof(struct termstr)*5); 

对此:

 typedef struct termstr* term; term* lptr = (term*)malloc(sizeof(term)*5); 

铸造malloc也是个好主意!

如果你想在它自己上使用typename termstr,你可以使用typedef:typedef struct {double a; 双b; } termstr;

在C中你也需要添加struct关键字,所以要么使用typedef将别名与’struct termstr’链接,要么你需要写一些类似的东西

 struct termstr* lptr = malloc(sizeof(struct termstr)*5); 

但是在C ++中你可以直接引用它作为’termstr’(读:不再需要struct关键字)。