问题描述
我试图创建结构元素的数组,如下所示:
I'm trying to create an array of struct elements, as shown below:
#include <stdio.h>
#include <stdlib.h>
struct termstr{
double coeff;
double exp;
};
int main(){
termstr* lptr = malloc(sizeof(termstr)*5);
return 0;
}
当我编译这个,我得到的错误如下:
When i compile this, i get errors as follows:
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)
然而,当我改变我的code到下面,它编译像往常一样:
However, when i change my code to the following, it compiles as usual:
#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(含类型名称的术语),改变了结构的名称termstr和我分配与长期记忆*为指针的类型。
I've added typedef (with type name as term), changed the name of struct to termstr and am allocating memory with term* as the type of pointer.
时的typedef总是需要这样的情况,即用于创建结构数组?如果不是,为什么是第一个code给人错误?是的typedef还需要创建和使用结构的一个实例?
Is typedef always required for such a situation i.e. for creating arrays of structs? If not, why was the first code giving errors? Is typedef also required to create and use a single instance of a struct?
推荐答案
第一种类型是不工作,因为你已经忘了结构
关键字之前 termstr
。你的数据类型为结构termstr
而不仅仅是 termstr
。当你的typedef
,所得到的名称用作结构termstr
的别名。
First type is not working because you have forgot struct
keyword before termstr
. Your data type is struct termstr
but not just termstr
. When you typedef
, the resulting name is used as an alias for struct termstr
.
即使你不需要这么做。使用的typedef
更好:
Even you don't need to do that. Using typedef
is better:
顺便说一句,不要忘记释放内存:
By the way don't forget to free the memory:
使用的typedef?
您的工作code应该是:
Your working code should be:
#include <stdio.h>
#include <stdlib.h>
struct termstr{
double coeff;
double exp;
};
int main(){
struct termstr* lptr = malloc(sizeof(struct termstr)*5);
free(lptr);
return 0;
}
这篇关于TYPEDEF需要结构声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!