Flexible array member

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

Flexible array member[1] is a feature 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, and it must be the last member of such a struct, as in the following example:

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

The sizeof operator on such a struct gives the size of the structure as if the flexible array member had been omitted except that it may have more trailing padding than the omission would imply. As such it is preferable to use offsetof when determining size for dynamic allocation, as in the following example:

   size = offsetof(struct vectord, arr) + nr_entries * sizeof(double);

When allocating such structures on the heap, it is generally required to reserve some space for the flexible array member, as in the following example:

struct vectord *allocate_vectord (size_t len) {
   struct vectord *vec = malloc(offsetof(struct vectord, arr) + len * sizeof(vec->arr[0]));

   if (!vec) {
       perror("malloc vectord failed");
       exit(EXIT_FAILURE);
   }

   vec->len = len;

   for (size_t i = 0; i < len; i++)
       vec->arr[i] = 0;

   return vec;
}

When using structures with a flexible array member, some convention regarding the actual size of that member should be defined. In the example above, the convention is that the member arr has len double-precision numbers.

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

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. ^ "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=841620347"
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