Error: flexible array element not at the end of the structure

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; 

The im get error is “error: the flexible array element is not at the end of the structure”. Im aware that this error can be resolved by moving int lost_index[] at the end of the structure. Why should the flexible member of the array be at the end of the structure? What reason?

As it is supposed, a duplicate of another question, in fact I did not find the answers that I really need, the answers in a similar question do not describe the reason behind the compiler in order to throw an error that I asked about.

thanks

+6
source share
1 answer

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

 int lost_index[]; int lost_index_size; 

wrong.

An exception to this rule is the so-called “flexible array element”, which is an array declared without size at the end of the struct . You must put it at the end of the struct so that memory can be allocated for it along with the struct itself. This is the only way the compiler could know the offsets of all data members.

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

+6
source

All Articles