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
structure_t my_array[5];
...
my_array[2].a = 0.0;
is the same as
(structure_t*)((void*)my_array + 2*sizeof(structure_t))->a = 0.0;
But what's the sizeof
our 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
void *result = malloc(arraysize * dimstruct);
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:
structure_t *p = result + i * dimstruct;
p->a = 0.0;
Note that result
is a void *
. If we declared it as structure_t *
the offset calculation would be wrong since it would use multiples of sizeof(structure_t)