flexible array member
   HOME

TheInfoList



OR:

C
struct In computer science, a record (also called a structure, struct, or compound data) is a basic data structure. Records in a database or spreadsheet are usually called "rows". A record is a collection of '' fields'', possibly of different data typ ...
data types may end with a flexible
array An array is a systematic arrangement of similar objects, usually in rows and columns. Things called an array include: {{TOC right Music * In twelve-tone and serial composition, the presentation of simultaneous twelve-tone sets such that the ...
member with no specified size: struct vectord ; Typically, such structures serve as the header in a larger, variable memory allocation: struct vectord *vector = malloc(...); vector->len = ...; for (int i = 0; i < vector->len; i++) vector->arr = ...; // transparently uses the right type (double)


Effect on struct size and padding

The sizeof 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 C99 (previously known as C9X) is an informal name for ISO/IEC 9899:1999, a past version of the C programming language standard. It extends the previous version ( C90) with new features for the language and the standard library, and helps impl ...
. In practice, compilers (e.g., GCC,
Microsoft Microsoft Corporation is an American multinational technology corporation producing computer software, consumer electronics, personal computers, and related services headquartered at the Microsoft Redmond campus located in Redmond, Washing ...
's) provided them well before C99 was standardized. Flexible array members are not officially part of
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
, but language extensionsE.g., are widely available.


References

{{Programming languages C (programming language) Data structures