在c中是否可以这样的结构声明
大家好, 我是 C 和学习结构的新手。我遇到了一种结构声明,并对它的验证有疑问...
struct a
{
int x;
struct a b;
}
有这样的结构声明可以吗?如果不是那么为什么?
Hii ALL,
i am new to c and learing structure.I came across to one of structure declaration and have a doubt on its validation ...
struct a
{
int x;
struct a b;
}
is it fine to have such structure declaration and if not then why??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,结构不能包含自身。这根本没有任何意义,因为生成的类型将无限大。
换句话说,您的结构包括其自身的一个实例,该实例又包括其自身的一个实例,该实例又包括其自身的一个实例,依此类推,无穷无尽……
从正式的角度来看,您正在尝试声明一个具有不完整类型的结构成员
b
。在 C 中声明不完整类型的结构成员是非法的。No. A structure cannot contain itself. This simply would not make any sense, since the resultant type will be infinitely large.
In other words, your structure includes an instance of itself, which in turn also includes an instance of itself, which in turn also includes an instance of itself, and so on and so forth ad infinitum...
Form the formal point of view, you are trying to declare a structure member
b
that has incomplete type. It is illegal to declare struct members of incomplete type in C.这将不起作用,因为如果结构是自包含的,则编译器无法确定结构的大小。
有效的方法是:
然后你有一个指向结构内部相同结构的指针。这可以用于链接列表等。
This will not work because the compiler cannot determine the size of your structure if it is self contained.
What works is:
Then you have a pointer to the same structure inside your structure. This can be used e.g. for linked lists.
编译此代码时,您将收到类似于以下内容的错误:
然而,使用
struct a *b
是完全没问题的。http://www.crasseux.com/books/ctutorial/Nested-structs.html
Compiling this you'll get an error similar to:
Using
struct a *b
, however, is perfectly fine.http://www.crasseux.com/books/ctutorial/Nested-structures.html