Effect on struct size and padding
Thesizeof
operator on such a struct
gives the size of the structure as if the flexible array member were empty. This may include padding added to accommodate the flexible member; the compiler is also free to re-use 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 /code>) or offsetof
, not sizeof
.
Availability
Flexible array members were officially standardized in C99. In practice, compilers (e.g., GCC, Microsoft
Microsoft Corporation is an American multinational corporation, multinational technology company, technology corporation producing Software, computer software, consumer electronics, personal computers, and related services headquartered at th ...
's) provided them well before C99 was standardized.
Flexible array members are not officially part of C++, but language extensionsE.g., are widely available.
References
{{Programming languages
C (programming language)
Data structures