我的结构看起来像这样:
typedef struct storage {
char ***data;
int lost_index[];
int lost_index_size;
int size;
int allowed_memory_key_size;
int allowed_memory_value_size;
int memory_size;
int allowed_memory_size;
} STORAGE;
我得到的错误是“错误:灵活的数组成员不在结构的末尾”。我知道这个错误可以通过在结构的末尾移动 int lost_index[]
来解决。为什么灵活的数组成员需要在结构的末尾?什么是原因?
因为这被认为是另一个问题的重复,实际上我没有找到我真正需要的答案,类似问题中的答案没有描述编译器抛出我询问的错误的原因。
谢谢
最佳答案
与函数参数中的数组声明不同,声明为 struct
或 union
的一部分的数组必须指定大小(有一个异常(exception)情况如下所述)。这就是为什么声明
int lost_index[];
int lost_index_size;
不正确。
此规则的异常(exception)是所谓的“灵活数组成员”,它是在 struct
末尾声明的没有大小的数组。您必须将它放在 struct
的末尾,以便它的内存可以与 struct
本身一起分配。这是编译器知道所有数据成员的偏移量的唯一方法。
如果编译器允许在 struct
中间使用灵活数组,则成员的位置以 size
、allowed_memory_key_size
和打开,将取决于您分配给 lost_index[]
数组的内存量。此外,编译器将无法在必要时填充 struct
以确保正确的内存访问。
关于c - 错误 : flexible array member not at end of struct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37164358/