Anuvansh Kumar
Anuvansh Kumar

Reputation: 25

Nested Structures memory allocation

I saw several questions on this topic .But my query couldn't be resolved.Links:

Structure memory allocation, Allocating memory for nested structure pointer,Understanding Nested Structures

Basically Memory is allocated when we create the instance of a structure not when we define it. So what if i create an object of another structure in this structure i.e. make something like this :

struct a{
int c;
};

struct b
{
struct a obj;
};

is now memory given to struct a object when we declare it in struct b?.(We can also do it through pointer but what if we do like this ).

Upvotes: 1

Views: 573

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134406

In your case, struct b is also a (another) declaration, just the same as struct a.

No memory allocation happens here. It's there for compiler to know, should a variable be defined of this type, how much memory to be allocated. Just because a member of a structure is another structure, it does not mean memory has to be allocated there. Once you have a variable of the type, memory allocation will take place.

Only thing to notice here, the inner structure type must be declared before it is used as a member of the outer type.

Upvotes: 2

Related Questions