Flexible array member

Flexible array member[1] is a feature introduced in the C99 standard of the C programming language (in particular, in section §6.7.2.1, item 16, page 103).[2] It is a member of a struct, which is an array without a given dimension, and it should be the last member of such a struct, as in the following example:

struct double_vector_st {
    unsigned length;
    double array[]; // the flexible array member should be last
};

The sizeof operator on such a struct is required to give the offset of the flexible array member. When allocating such structures on the heap, it is generally required to reserve some space for the flexible array member, as in the following example:

struct double_vector_st* allocate_double_vector(unsigned len) {
   struct double_vector_st* vec = malloc(sizeof(struct double_vector_st) + len * sizeof(double));
 
   if (!vec) {
       perror("malloc double_vector_st failed");
       exit(EXIT_FAILURE);
   }
 
   vec->length = len;
 
   for (unsigned ix = 0; ix < len; ix++)
       vec->array[ix] = 0.0;
 
   return vec;
}

When using structures with a flexible array member, some convention regarding the actual size of that member should be defined. In the example above, the convention is that the member array has length double-precision numbers.

In previous standards of the C language, it was common to declare a zero-sized array member instead of a flexible array member. The GCC compiler explicitly accepts zero-sized arrays for such purposes.[3]

C++ does not have flexible array members; there is a std::dynarray proposal providing a similar functionality, but it is not part of the C++11 standard.,[4] albeit GCC accepts them also in C++ code.

References