繁体   English   中英

结构声明中需要typedef

[英]typedef required in struct declaration

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

#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创建和使用结构的单个实例?

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

甚至您也不需要这样做。 使用typedef更好:

顺便说一句,不要忘记释放内存:

阅读为什么要使用typedef?

您的工作代码应为:

#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;
}

它应该是:

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关键字)。

暂无
暂无

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

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