Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct inside struct

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

like image 863
sok Avatar asked Dec 26 '12 12:12

sok


People also ask

Can I have a struct inside a struct?

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.

How do you write a struct in a struct?

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.

Can we define structure inside structure?

A structure inside another structure is called nested structure.

Can we declare struct inside main?

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.


2 Answers

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

like image 107
che Avatar answered Oct 01 '22 01:10

che


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

like image 30
Cobusve Avatar answered Oct 01 '22 01:10

Cobusve