灵活数组成员的使用无效(与其他人不同)

Invalid use of flexible array member (Not as the others)

所以我有这两个结构:

typedef struct item { 
    const char *label;
    int value;
} Item;

typedef struct item_coll { 
    size_t length; 
    Item items[]; 
} ItemColl;

我想这样做:

 int main() {

    Item a = {"A", 10};
    Item b = {"B", 20};
    Item c = {"C", 30};

    Item items[] = {a, b, c};

    size_t length = sizeof(items)/sizeof(items[0]);

    ItemColl *column = malloc (sizeof(column) + length * sizeof(Item));

    column -> length = length;
    column -> items = items;

    printf("%ld\n", column -> length);

    return 0;
}

但我在此处收到错误 "Invalid use of flexible array member":

column -> items = items;

据我所知,我正在分配所需的 space,这就是为什么我不明白问题所在。

我已经看到另外 2 个具有此标题的帖子,但其中 none 解决了我的问题,因为我已经尝试了这些问题的答案。

正如其他人所提到的,您不能将一个数组分配给另一个数组。

部分原因是编译器无法始终知道数组的长度,尤其是对于灵活的数组成员。 (例如)此外,源或目标可能是指针。为了保持一致,它只是标记它。

所以,改变:

column->items = items;

至:

for (int idx = 0;  idx < length;  ++idx)
    column->items[idx] = items[idx];

或者,使用 memcpy:

memcpy(column->items, items, sizeof(column->items[0]) * length);

旁注:

如果 column->items 是一个 指针 (例如 Item *items),则执行:

column->items = items;

有效。但是,它 不会 复制 。它只会将结构的指针设置为函数作用域数组的地址 items。这不是想要的结果。