在 GCC 中使用结构并出现错误
相同的代码在 TURBO C 中运行。
struct details
{
char name[20];
int year;
float price;
}my_str;
details book1[10];
产生此错误。如何解决这个问题?
ram.c: In function ‘main’:
ram.c:11:1: error: ‘details’ undeclared (first use in this function)
ram.c:11:1: note: each undeclared identifier is reported only once for each function it appears in
The same code ran in TURBO C.
struct details
{
char name[20];
int year;
float price;
}my_str;
details book1[10];
This error is produced. How can this be fixed?
ram.c: In function ‘main’:
ram.c:11:1: error: ‘details’ undeclared (first use in this function)
ram.c:11:1: note: each undeclared identifier is reported only once for each function it appears in
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
需要...
needs to be ...
您需要像这样进行结构变量声明:
这是因为
details
没有经过typedef
编辑,因此您不能像用户定义类型一样使用它,因此您需要使用struct
关键字。请注意,在上面的定义中
my_str
是一个structDetails
类型的变量(分配的对象)您还可以执行以下操作:
然后执行:
这与上面相同。这里请注意,
my_str
不是变量(对象),而是您使用typedef
关键字定义的类型名称。此后,编译器将知道您正在使用my_str
作为您创建的复合结构数据类型的新用户定义类型名称,因此您可以使用my_str
直接而不是使用结构详细信息
You need to make the structure variable declaration like this:
This is because the
details
is nottypedef
ed, and therefore you cannt use it like a user defined type, and therefore you need to use thestruct
keyword.Note that, in your above definition
my_str
is a variable (allocated object) of typestruct details
You can also do:
And then do:
This is same as above. Here note that, the
my_str
is not a variable (object) but the typename which you have defined with thetypedef
keyword. After this point the compiler would know that you are using themy_str
as a new user defined type name for the composite structure data type you have created, and therefore you can usemy_str
directly instead of usingstruct details
这对于 C 来说更正确一些:
This is a a bit more correct in terms of C:
有两种方法可以解决此问题:
将第二行更改为:
或者您可以将声明更改为:
C 与 C++ 略有不同,因此您不能以完全相同的方式声明结构。
There are two ways to fix this:
Change second line to this:
Or you can change the declaration to:
C is slightly different from C++, so you can't declare structs quite the same way.