错误:弹性阵列成员不在结构结尾 [英] error: flexible array member not at end of struct

查看:116
本文介绍了错误:弹性阵列成员不在结构结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的结构看起来像这样:

My Struct looks like this:

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的末尾来解决此错误.为什么灵活数组成员必须位于struct的末尾?是什么原因?

The error im getting is "error: flexible array member not at end of struct". Im aware that this error can be solved by moving int lost_index[] at the end of struct. Why should flexible array member need to be at the end of struct? What is reason?

由于这是另一个问题的重复,实际上我没有找到我真正需要的答案,类似问题中的答案也没有描述原因,后者在编译器后面抛出了我所问的错误.

As this is assumed duplicate of another question, actually i didn't find answers that i actually needed, answers in similar question dont describe the reason which stands behind compiler to throw error i asked about.

谢谢

推荐答案

与函数参数中的数组声明不同,作为 struct union 的一部分声明的数组必须具有指定的大小(下面将描述一个例外).这就是为什么要声明

Unlike array declarations in function parameters, array declared as part of a struct or a union must have a size specified (with one exception described below). That is why declaring

int lost_index[];
int lost_index_size;

不正确.

此规则的例外是所谓的柔性数组成员",它是在 struct 的末尾声明没有大小的数组.您必须将其放置在 struct 的末尾,以便可以将其内存与 struct 本身一起分配.这是编译器知道所有数据成员的偏移量的唯一方法.

The exception to this rule is so-called "flexible array member", which is an array declared with no size at the end of the struct. You must place it at the end of the struct so that the memory for it could be allocated along with the struct itself. This is the only way the compiler could know the offsets of all data members.

如果编译器允许在 struct 中间放置灵活的数组,则成员的位置应以 size allowed_memory_key_size 和取决于您分配给 lost_index [] 数组的内存量.而且,编译器将无法在必要的地方填充 struct 来确保适当的内存访问.

If the compiler were to allow flexible arrays in the middle of a struct, the location of members starting with size, allowed_memory_key_size, and on, would be dependent on the amount of memory that you allocate to lost_index[] array. Moreover, the compiler would not be able to pad the struct where necessary to ensure proper memory access.

这篇关于错误:弹性阵列成员不在结构结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆