user2131316 user2131316 - 1 year ago 113
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download