user2131316 user2131316 - 14 days ago 9
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
name
array first and then we operate
nim
array later, then the
nim[1]
will overwrite the
name
array, then how to solve it?

Answer

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.