Struct inside struct
Either do the forward declaration of struct FRIDGE;
Or,
give the definition of FRIDGE
before using it in struct PERSON
You have to use members of FRIDGE
, after removing all warnings and errors. Declare FRIDGE
before PERSON
me.fridge.number = 1
EDITED: I found the bug. You are using anonymous structure, so you should not use the struct
keyword but use the typedef
ed name.
Change struct FRIDGE fridge
to FRIDGE fridge
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
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).