Search code examples
c

C: Memory Allocation on Stack for Nested Structures


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


Solution

  • Yes, declaring a Parent variable allocates space for all members, including the nested Child. Accessing nested members like parent.child.a is valid and doesn't require separate allocation.

    #include <stdio.h>
    
    typedef struct Child {
        int a;
        char b[10];
    } Child;
    
    typedef struct Parent {
        int c;
        char d[10];
        Child child;
    } Parent;
    
    int main() {
        Parent parent;
        parent.child.a = 5;  // Valid: Space for child.a is already allocated.
        printf("%d\n", parent.child.a); // Output: 5
        return 0;
    }