代码之家  ›  专栏  ›  技术社区  ›  9-Pin

C: 嵌套结构的堆栈内存分配

c
  •  2
  • 9-Pin  · 技术社区  · 7 月前

    假设我定义了一个结构类型如下:

    typedef struct Child {
        int a;
        char b[10];
    } Child;
    

    因为编译器知道所有内容的空间要求 Child 的成员,我不需要使用 malloc .

    Child child; /* Allocates space on the stack for child and its members. */
    

    接下来,我定义一个结构类型 Parent 这包括 儿童 .

    typedef struct Parent {
        int c;
        char d[10];
        Child child;
    } Parent;
    

    当我声明一个类型为的变量时 起源 ,是否为父结构和子结构的成员分配了足够的堆栈内存?

    Parent parent; /* Allocates space for all members of parent, including the nested child? */
    parent.child.a = 5; /* Is this assignment guaranteed to work? */
    

    (这是对问题的阐述 Nested Structures memory allocation .)

    2 回复  |  直到 7 月前
        1
  •  2
  •   Darth-CodeX    7 月前

    是的,宣布 Parent 变量为所有成员分配空间,包括嵌套的 Child .访问嵌套成员,如 parent.child.a 有效,不需要单独分配。

    #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;
    }
    
        2
  •  0
  •   Barmar    7 月前

    作为 Parent struct包含整个 Child struct,当你定义一个具有 起源 类型,它将为所有成员提供空间,包括 child .