i would like create a array of structure which have a dynamic array :
typedef struct{
float a;
int b[];
}structure_t;
n = ...;
size_t dimstruct = sizeof(structure_t)+n*sizeof(int);
structure_t * resultat = malloc(dimstruct);
How to create a dynamic array of this structure and contiguous in memory?
Thx!
You have the right idea. The code you have written allocates space for one struct with a variable-size array using a C99 style flexible member. The same trick would work with a C90-style zero-length array or 1-sized array.
The struct commonly includes a member to specify the size of the variable-length portion, though that is obviously not a requirement. But you can see how this is a problem for making an array of these structs.
Generally
is the same as
But what’s the
sizeofour dynamic struct? Whatever it happens to evaluate to, it is clearly what we want, since it does not include the variable portion.So we can allocate the array of these structs by doing
and it will be contiguous. But we can’t use array indexing syntax, since the size of the struct is undefined. Instead we index manually, as hinted above:
Note that
resultis avoid *. If we declared it asstructure_t *the offset calculation would be wrong since it would use multiples ofsizeof(structure_t)