Struct inside struct

2020-02-26 06:47发布

问题:

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

回答1:

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).



回答2:

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 typedefed name.

Change struct FRIDGE fridge to FRIDGE fridge



回答3:

Either do the forward declaration of struct FRIDGE;

Or,

give the definition of FRIDGE before using it in struct PERSON



回答4:

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