了解包含结构的结构以及如何正确初始化它们

时间:2016-10-22 12:52:00

标签: c arrays pointers struct

我试图了解如何正确初始化包含其他结构的结构(特别是结构数组!)。我做了一个小概述,代表了我目前的理解,并想问这是正确或错误的做法:

(注意,为了简洁起见,省略了malloc()的破坏方法和检查。)

最简单的结构只包含静态变量:

typedef struct simple {
    int variable;
} Simple;

Simple *create_simple(int value) {
    Simple *simple = malloc(sizeof(Simple));
    simple->variable = value;
    return simple;
}

使用像数组这样的动态变量需要额外的分配:

typedef struct array {
    size_t length;
    int *element;
} Array;

Array *create_array(size_t length) {
    Array *array = malloc(sizeof(Array));
    array->length = length;
    array->element = malloc(length * sizeof(int));
    return array;
}

包含指向其他结构的指针的结构也是如此。在这种情况下,我们需要单独为内部结构分配内存:

typedef struct container {
    Simple *internal;
} Container;

Container *create_container(int value) {
    Container *container = malloc(sizeof(Container));
    // Is this correct? Or should I just malloc(sizeof(Simple))?
    container->internal = create_simple(value);
    return container;
}

更复杂的是包含动态结构指针数组的结构:

typedef struct struct_array {
    size_t length;
    Simple **element;
} StructArray;

StructArray *create_struct_array(size_t length) {
    StructArray *structArray = malloc(sizeof(Array));
    structArray->length = length;
    // Would I alternatively need to loop over 
    // the array and call create_simple() on each index?
    structArray->element = malloc(length * sizeof(Simple));
    return structArray;
}

现在可以有任何嵌套深度的结构:

typedef struct complex_container {
    size_t length;
    StructArray *element;
} ComplexContainer;

ComplexContainer *create_complex_container(size_t length) {
    ComplexContainer *complexContainer = malloc(sizeof(ComplexContainer));
    complexContainer->length = length;
    // Is this valid? My create_struct_array function should 
    // allocate the memory?
    complexContainer->element = create_struct_array(length);
    return complexContainer;
}

0 个答案:

没有答案