Suppose I define a structure type as follows:
typedef struct Child {
int a;
char b[10];
} Child;
Because the compiler knows the space requirements for all of Child
's members, I don't need to use malloc
.
Child child; /* Allocates space on the stack for child and its members. */
Next, I define a structure type Parent
that includes Child
.
typedef struct Parent {
int c;
char d[10];
Child child;
} Parent;
When I declare a variable of type Parent
, is enough stack memory allocated for members of both the parent and the child structures?
Parent parent; /* Allocates space for all members of parent, including the nested child? */
parent.child.a = 5; /* Is this assignment guaranteed to work? */
(This is an elaboration of the question Nested Structures memory allocation.)
Suppose I define a structure type as follows:
typedef struct Child {
int a;
char b[10];
} Child;
Because the compiler knows the space requirements for all of Child
's members, I don't need to use malloc
.
Child child; /* Allocates space on the stack for child and its members. */
Next, I define a structure type Parent
that includes Child
.
typedef struct Parent {
int c;
char d[10];
Child child;
} Parent;
When I declare a variable of type Parent
, is enough stack memory allocated for members of both the parent and the child structures?
Parent parent; /* Allocates space for all members of parent, including the nested child? */
parent.child.a = 5; /* Is this assignment guaranteed to work? */
(This is an elaboration of the question Nested Structures memory allocation.)
Share Improve this question asked Jan 29 at 17:36 9-Pin9-Pin 4502 silver badges11 bronze badges 5 |1 Answer
Reset to default 0As the Parent
struct contains the whole Child
struct, when you define an object having the Parent
type, it will have space for all of its members, including child
.
Child
type-alias, it's like any other native type likeint
. I assume you don't have the same question for thec
ord
members? There's really no difference between them andchild
. – Some programmer dude Commented Jan 29 at 17:57parent
is defined in returns. SoX *NewX() { X x; return &x; }
is not valid in C. – mevets Commented Jan 29 at 21:02