【发布时间】:2013-06-15 14:54:57
【问题描述】:
我正在尝试创建一个结构元素数组,如下所示:
#include <stdio.h>
#include <stdlib.h>
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 <stdio.h>
#include <stdlib.h>
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 来创建和使用结构的单个实例?
【问题讨论】:
-
不,你不需要 typedef。你也可以不用,但你需要添加 struct 关键字:
struct termstr *lptr = malloc(5 * sizeof *lptr);