Flexible array member in C-structure

The C FAQ answers precisely this question. The quick answer is that this structure will include the double array inside the structure rather than a pointer to an array outside the structure. As a quick example, you could use your structure as in this example:

struct s mystruct = malloc(sizeof(struct s) + 5 * sizeof(double));
s.n = 12;
s.d[0] = 4.0;
s.d[1] = 5.0;
s.d[2] = 6.0;
s.d[3] = 7.0;
s.d[4] = 8.0;

And so on – the size of the array you care about is included in the allocation, and then you can use it just like any array. Normally such a type contains the size as part of the structure, since using the + trick to skip through an array of type s will be necessarily complicated by this situation.

To your added question ‘how is this construct any more or less powerful than keeping a [pointer] as the 2nd element?’, it’s no more powerful per se, but you don’t need to keep a pointer around, so you would save at least that much space – also when you are copying the structure, you would also copy the array, rather than a pointer to an array – a subtle difference sometimes, but very important other times. ‘You-can-do-it-in-multiple-ways’ is probably a good explanation, but there are cases where you would specifically want one design or the other.

Leave a Comment