user2131316 user2131316 - 1 month ago 20
C Question

multiple flexible array in a struct in C?

I have multiple flexible arrays in s struct in c:

typedef struct
int a;
float b;
} Name;

typedef struct
int c;
int d;
int e;
} NIM;

typedef struct
int age;
int time;
Name name[1];
NIM nim[1];
} EthgenSig;

if we have need to allocate memory like this:

malloc(sizeof(EthgenSig) + sizeof(Name) * 10);

how the memory will be allocated and if we operator
array first and then we operate
array later, then the
will overwrite the
array, then how to solve it?


You can't have more than one flexible-array member for the exact reason you pointed out.

At most, if you need your data to be kept all in the same memory block, you can make name and nim pointers and set where they point to the correct locations after allocation (making sure not to break any alignment constraint), but the simplest (and most sensible) thing is to just allocate separately the arrays for name and nim.