Flexible array member
C struct data types may end with a flexible array member[1] with no specified size: struct vectord {
short 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
};
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[i] = ...; // transparently uses the right type (double)
Effect on struct size and paddingThe It is common to allocate 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 As the array may start in the padding before the end of the structure, its content should always be accessed via indexing ( AvailabilityFlexible array members were officially standardized in C99.[4] In practice, compilers (e.g., GCC,[5]MSVC[6]) provided them well before C99 was standardized. Flexible array members are not officially part of C++, but language extensions[7] are widely available. References
|
Portal di Ensiklopedia Dunia