C语言 C - 字段类型不完整
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41915049/
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
C - Field has incomplete type
提问by user1787812
In the below representation,
在下面的表示中,
struct Cat{
char *name;
struct Cat mother;
struct Cat *children;
};
Compiler gives below error for second field, but not third field,
编译器为第二个字段提供以下错误,但不是第三个字段,
error: field ‘mother' has incomplete type
struct Cat mother;
^
How to understand this error?
如何理解这个错误?
回答by StoryTeller - Unslander Monica
The error means that you try and add a member to the structof a type that isn't fully defined yet, so the compiler cannot know its size in order to determine the objects layout.
该错误意味着您尝试向struct尚未完全定义的类型添加成员,因此编译器无法知道其大小以确定对象布局。
In you particular case, you try and have struct Cathold a complete object of itself as a member (the motherfield). That sort of infinite recursion in type definition is of course impossible.
在您的特定情况下,您尝试struct Cat将一个完整的对象作为成员(mother字段)持有。类型定义中的那种无限递归当然是不可能的。
Nevertheless, structures can contain pointers to other instances of themselves. So if you change your definition as follows, it will be a valid struct:
然而,结构可以包含指向自身其他实例的指针。因此,如果您按如下方式更改定义,它将是有效的struct:
struct Cat{
char *name;
struct Cat *mother;
struct Cat *children;
};

