11

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 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.

Thanks

Strahinja Djurić
  • 394
  • 1
  • 2
  • 14
  • 2
    Possible duplicate of [What is the cause of flexible array member not at end of struct error?](http://stackoverflow.com/questions/11180378/what-is-the-cause-of-flexible-array-member-not-at-end-of-struct-error) – jboockmann May 11 '16 at 13:43
  • @pytheos Not really. This question asks for the _reason_ behind the way it is designed. :) – Sourav Ghosh May 11 '16 at 13:44
  • In that answer i didn't find explanation, why its caused, what makes compilers to throw this error. – Strahinja Djurić May 11 '16 at 13:45
  • 1
    @StrahinjaDjurić, actually the last answer there held all the info you need. – HighPredator May 11 '16 at 14:12
  • The compilers flags an error because the language requires the member to be at the end and the compiler is following the rules of the language. Now the question should be: "why does the _language_ require it?" – chux - Reinstate Monica May 11 '16 at 14:12

1 Answers1

13

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;

is incorrect.

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.

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523