简体   繁体   English

在c中这样的结构声明是否可能

[英]Is it possible such structure declaration In c

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 ... 嗨,大家好,我是c和learing structure的新手。我遇到了一种结构声明,并对它的验证有疑问...

struct a
{ 
int x;
struct a b;
}

is it fine to have such structure declaration and if not then why?? 有这样的结构声明可以吗?

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 . 从形式上看,您试图声明一个类型不完整的结构成员b It is illegal to declare struct members of incomplete type in C. 在C中声明不完整类型的struct成员是非法的。

This will not work because the compiler cannot determine the size of your structure if it is self contained. 这将不起作用,因为如果编译器是自包含的,则编译器无法确定其大小。

What works is: 起作用的是:

struct a
{
int x;
struct a* b;
}

Then you have a pointer to the same structure inside your structure. 然后,您有一个指向结构内部相同结构的指针。 This can be used eg for linked lists. 例如,可用于链接列表。

Compiling this you'll get an error similar to: 编译此错误将得到类似于以下内容的错误:

src.c: In function `main':
src.c:4: field `b' has incomplete type

Using struct a *b , however, is perfectly fine. 但是,使用struct a *b非常好。

http://www.crasseux.com/books/ctutorial/Nested-structures.html http://www.crasseux.com/books/ctutorial/Nested-structures.html

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

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