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
A nested structure in C is a structure within structure. One structure can be declared inside another structure in the same way structure members are declared inside a structure.
Syntax of structstruct structureName { dataType member1; dataType member2; ... }; For example, struct Person { char name[50]; int citNo; float salary; }; Here, a derived type struct Person is defined.
A structure inside another structure is called nested structure.
Second, there is no rule as such, You can define wherever you want. It is all about the scope of the definition. If you define the structure inside main() , the scope is limited to main() only. Any other function cannot see that definition and hence, cannot make use of that structure definition.
struct FRIDGE
is something different than FRIDGE
.
You need to either use type FRIDGE
in your other structure.
typedef struct {
int age;
FRIDGE fridge;
} PERSON;
or define your fridge as struct FRIDGE
struct FRIDGE {
int number;
};
Also, the structure may have to be defined before you use it (e.g. above the person).
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.
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/
But in short what you really want to do is leave out the typedef's like this
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.
https://yarchive.net/comp/linux/typedefs.html
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