C语言 结构内结构
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14040612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Struct inside struct
提问by sok
I must create a Person and each Person should have a Fridge. Is this the best way of doing it? If so what am I doing wrong? Thanks in advance.
我必须创建一个人,每个人都应该有一个冰箱。这是最好的方法吗?如果是这样,我做错了什么?提前致谢。
typedef struct {
int age;
struct FRIDGE fridge;
} PERSON;
typedef struct {
int number;
} FRIDGE;
FRIDGE fr;
fr.number=1;
PERSON me;
me.name=1;
me.fridge = fr;
This gives me the following error:
这给了我以下错误:
error: field ‘fridge' has incomplete type
错误:字段“冰箱”的类型不完整
回答by che
struct FRIDGEis something different than FRIDGE.
struct FRIDGE是不同的东西FRIDGE。
You need to either use type FRIDGEin your other structure.
您需要FRIDGE在其他结构中使用类型。
typedef struct {
int age;
FRIDGE fridge;
} PERSON;
or define your fridge as struct FRIDGE
或将您的冰箱定义为 struct FRIDGE
struct FRIDGE {
int number;
};
Also, the structure may have to be defined before you use it (e.g. above the person).
此外,结构可能必须在您使用之前定义(例如在人上方)。
回答by manav m-n
You have to use members of FRIDGE, after removing all warnings and errors. Declare FRIDGEbefore PERSON
FRIDGE删除所有警告和错误后,您必须使用 , 的成员。FRIDGE提前申报PERSON
me.fridge.number = 1
me.fridge.number = 1
EDITED: I found the bug. You are using anonymous structure, so you should not use the structkeyword but use the typedefed name.
编辑:我发现了错误。您使用的是匿名结构,因此不应使用struct关键字而应使用typedefed 名称。
Change struct FRIDGE fridgeto FRIDGE fridge
更改struct FRIDGE fridge为FRIDGE fridge
回答by Omkant
Either do the forward declaration of struct FRIDGE;
要么做前向声明 struct FRIDGE;
Or,
或者,
give the definition of FRIDGEbefore using it in struct PERSON
FRIDGE在 struct 中使用之前给出定义PERSON
回答by Cobusve
Using typedefs with your structs will get you into this kind of tangle. The struct keyword in front of a struct tag identifier is how structs are supposed to be used, this is also more explicit and easier to read.
将 typedef 与您的结构一起使用会让您陷入这种纠结。struct 标记标识符前面的 struct 关键字是应该如何使用结构的,这也更明确且更易于阅读。
There is a long and good blog post with all the details here https://www.microforum.cc/blogs/entry/21-how-to-struct-lessons-on-structures-in-c/
这里有一篇很长很不错的博客文章,其中包含所有详细信息 https://www.microforum.cc/blogs/entry/21-how-to-struct-lessons-on-structures-in-c/
But in short what you really want to do is leave out the typedef's like this
但简而言之,您真正想要做的是像这样省略 typedef
struct FRIDGE; // This is a forward declaration, now an incomplete type
struct PERSON{
int age;
struct FRIDGE fridge;
};
struct FRIDGE{
int number;
};
struct FRIDGE fr;
fr.number=1;
struct PERSON me;
me.name=1;
me.fridge = fr;
Linus Torvalds also went on about this once, very solid reasoning why using typedefs on all your structs is confusing and bad.
Linus Torvalds 也谈到了这一次,非常可靠的推理为什么在所有结构上使用 typedef 是令人困惑和糟糕的。

