C struct data types may end with a flexible array member with no specified size:

typedef struct { size_t len; // there must be at least one other data member double arr[]; // the flexible array member must be last // The compiler may reserve extra padding space here, like it can between struct members } DoubleArray;

Typically, such structures serve as the header in a larger, variable memory allocation:

// see section on size and padding DoubleArray* darray = malloc(sizeof(DoubleArray) + ... * sizeof(double)); darray->len = ...; for (int i = 0; i < darray->len; i++) { darray->arr[i] = ...; // transparently uses the right type (double) }

Effect on struct size and padding

The sizeof operator on such a struct gives the size of the struct as if the flexible array member were not present. This may include padding added to accommodate the flexible member; the compiler is also free to reuse such padding as part of the array itself.

It is common to allocate sizeof(struct) + array_len * sizeof(array element) bytes.

This is not wrong, but it may allocate a few more bytes than necessary: the compiler may be re-purposing some of the padding that is included in sizeof(struct). Should this be a concern, macros are available to compute the minimum size while ensuring that the compiler's padding is not disrupted.

As the array may start in the padding before the end of the structure, its content should always be accessed via indexing (arr[i]) or offsetof, not sizeof.

History

Flexible array members were officially standardized in C99.C99 section §6.7.2.1, item 16, page 103, https://www.open-std.org/jtc1/sc22/WG14/www/docs/n1256.pdf In practice, compilers (e.g., GCC, MSVC) provided them well before C99 was standardized. Widely employed prior to the standardization of flexible array members, the use of such extensions was known as the struct hack. The term "struct hack" is also used to refer to the use of a standard array member of length 1 as if it were a flexible array member.

Flexible array members are not officially part of C++, but language extensionsE.g., are widely available.

References