Flexible array member

From Wikipedia, the free encyclopedia
Jump to navigation Jump to search

Flexible array members[1] were 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. It must be the last member of such a struct and it must be accompanied by at least one other member, as in the following example:

struct vectord {
    size_t len;
    double arr[]; // the flexible array member must be last
};

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] = ...;

The sizeof operator on such a struct gives the size of the structure as if the flexible array member was 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 [3].

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

This is not wrong, however 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[4] 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.

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.[5]

C++ does not have flexible array members.

References

  1. ^ "Lesser known C features". Retrieved December 30, 2014.
  2. ^ http://www.open-std.org/jtc1/sc22/WG14/www/docs/n1256.pdf
  3. ^ "flexible array member". Jens Gustedt's Blog. 2011-03-14. Retrieved 2018-10-09.
  4. ^ "P99: Flexible array members". p99.gforge.inria.fr. Retrieved 2018-10-09.
  5. ^ "Zero Length - Using the GNU Compiler Collection (GCC)". Retrieved December 30, 2014.
Retrieved from "https://en.wikipedia.org/w/index.php?title=Flexible_array_member&oldid=867233681"
This content was retrieved from Wikipedia : http://en.wikipedia.org/wiki/Flexible_array_member
This page is based on the copyrighted Wikipedia article "Flexible array member"; it is used under the Creative Commons Attribution-ShareAlike 3.0 Unported License (CC-BY-SA). You may redistribute it, verbatim or modified, providing that you comply with the terms of the CC-BY-SA