c - 错误 : flexible array member not at end of struct

标签 c arrays struct

我的结构看起来像这样:

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[] 来解决。为什么灵活的数组成员需要在结构的末尾?什么是原因?

因为这被认为是另一个问题的重复,实际上我没有找到我真正需要的答案,类似问题中的答案没有描述编译器抛出我询问的错误的原因

谢谢

最佳答案

与函数参数中的数组声明不同,声明为 structunion 的一部分的数组必须指定大小(有一个异常(exception)情况如下所述)。这就是为什么声明

int lost_index[];
int lost_index_size;

不正确。

此规则的异常(exception)是所谓的“灵活数组成员”,它是在 struct 末尾声明的没有大小的数组。您必须将它放在 struct 的末尾,以便它的内存可以与 struct 本身一起分配。这是编译器知道所有数据成员的偏移量的唯一方法。

如果编译器允许在 struct 中间使用灵活数组,则成员的位置以 sizeallowed_memory_key_size 和打开,将取决于您分配给 lost_index[] 数组的内存量。此外,编译器将无法在必要时填充 struct 以确保正确的内存访问。

关于c - 错误 : flexible array member not at end of struct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37164358/

相关文章:

JavaScript 2D 数组未捕获类型错误

c - 将一个结构内部的 int 右对齐到另一个结构内部

c - 关于结构体指针及其工作原理

c - 在编译时为结构构建类型描述表

c - c使用fscanf()从文本文件中读取单独的单词

java - 如何从java中的另一个方法引用/定义数组?

C多个文件,打印数组的段错误

c - 无法释放父结构的 child

pointers - 扫描错误 : sql: Scan error on column index 11: destination not a pointer

C TCP套接字,使用select后 'send'可以返回0吗?