Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error: flexible array member not at end of struct

Tags:

arrays

c

struct

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

like image 620
Strahinja Djurić Avatar asked May 11 '16 13:05

Strahinja Djurić


1 Answers

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.

like image 60
Sergey Kalinichenko Avatar answered Nov 11 '22 14:11

Sergey Kalinichenko