初始化嵌套变量数组成员

问题描述 投票:0回答:1
typedef struct nestedStruct
{
    int a;
    int b;
    char* name;
} nestedStruct;

typedef myStruct
{
    int count;
    nestedStruct myNestedStruct[];
}

我需要定义灵活的结构,其中包含许多嵌套结构和结构本身。然后我需要显式地初始化它们,就像

myStruct realStruct
{
    2,
    { 1, 2, "name 1" },
    { 3, 4, "name 2" }
} realStruct;

将会有许多应用程序按照他们需要的宽度使用该结构。

我很清楚这种语法不正确,我找不到正确的语法,并且this明确指出这是不可能的。为什么?

有什么建议我可以制作数据结构的“总线”而不将它们分成多个指针,以便能够将指向此类结构的单个指针传递给函数,并且这些函数知道这些总线的布局而无需附加参数。

编辑:

这个有效

myStruct realStruct
{
    2,
    {
        { 1, 2, "name 1" },
        { 3, 4, "name 2" }
    }
} realStruct;

但是有迂腐的警告

warning: initialization of a flexible array member [-Wpedantic]

嗯,警告是为了让我知道我可能做错了什么。有没有办法告诉编译器这就是我真正想做的事情 - 根本不抑制警告?

c struct flexible-array-member
1个回答
0
投票

灵活的数组成员是为了动态内存分配而发明的。

typedef struct nestedStruct
{
    int a;
    int b;
    char* name;
} nestedStruct;

typedef struct myStruct
{
    size_t count;
    nestedStruct myNestedStruct[];
}myStruct;



myStruct *init(void)
{
    myStruct *str = malloc(sizeof(*str) + 2 * sizeof(str -> myNestedStruct[0]));
    if(str)
    {
        str -> count = 2;
        str -> myNestedStruct[0] = (nestedStruct){ 1, 2, "name 1" };
        str -> myNestedStruct[1] = (nestedStruct){ 3, 4, "name 2" };
    }
    return str;
}

myStruct *init1(size_t size, nestedStruct *initData)
{
    myStruct *str = malloc(sizeof(*str) + size * sizeof(str -> myNestedStruct[0]));
    if(str)
    {
        str -> count = size;
        memcpy(str -> myNestedStruct, initData, size * sizeof(*initData));
    }
    return str;
}

myStruct *add(myStruct *str, nestedStruct *data)
{
    size_t newsize = str ? str -> count + 1 : 1;
    str = realloc(str, sizeof(*str) + newsize * sizeof(str -> myNestedStruct[0]));
    if(str)
    {
        str -> count = newsize;
        str -> myNestedStruct[newsize - 1] = *data;
    }
    return str;
}


int main(void)
{
    myStruct *s1 = init();
    myStruct *s2 = init1(2, (nestedStruct[]){{ 1, 2, "name 1" },{ 3, 4, "name 2" }});

    myStruct *s3 = add(NULL, (nestedStruct[]){{ 1, 2, "name 1" }});
    /* yuo should check if those functions did not return NULL */
    myStruct *tmp = add(s3, (nestedStruct[]){{ 3, 4, "name 2" }});
    if(tmp) s3 = tmp;

    free(s1);
    free(s2);
    free(s3);
}
© www.soinside.com 2019 - 2024. All rights reserved.