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?
The error means that you try and add a member to the struct of a type that isn't fully defined yet, so the compiler cannot know its size in order to determine the objects layout. In you particular case, you try and have struct Cat hold a complete object of itself as a member (the mother field).
An incomplete type is a type that describes an identifier but lacks information needed to determine the size of the identifier. An incomplete type can be: A structure type whose members you have not yet specified. A union type whose members you have not yet specified.
The error means that you try and add a member to the struct
of a type that isn't fully defined yet, so the compiler cannot know its size in order to determine the objects layout.
In you particular case, you try and have struct Cat
hold a complete object of itself as a member (the mother
field). That sort of infinite recursion in type definition is of course impossible.
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 Cat{
char *name;
struct Cat *mother;
struct Cat *children;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With