0

Is it legal to define array with 0 elements in structure or it is allowed as side effect by compilers? For example:

typedef struct _my_str
{
  int    len;
  double total;
  double tax;
  int    items;
  double item_price[0];
} my_struct;
i486
  • 6,236
  • 3
  • 23
  • 39
  • 2
    I think it is legal in C, but it is an extension in C++ – Jarod42 Dec 17 '15 at 10:19
  • [gcc extension](http://stackoverflow.com/q/26209190/1708801) – Shafik Yaghmour Dec 17 '15 at 10:19
  • 2
    @HappyCoder In the above example, you can have variable number of `item_price` elements and array of variable length structures (processed via pointer, not index). – i486 Dec 17 '15 at 10:28
  • 1
    @HappyCoder, the primary use case is to avoid doubling the memory management overhead when you want a variable length array closely associated with a small amount of other data. The ordinary approach would allocate the struct including a pointer to a second allocation for the variable length array. The efficient approach allocates memory for the struct plus the array in one chunk. – JSF Dec 17 '15 at 10:29
  • Note that there's a difference between zero size arrays and the C feature _flexible array members_. Zero sized arrays are forbidden in both C and C++. – Lundin Dec 17 '15 at 10:36
  • For example, `BITMAPINFO` Win32 structure may use such definition. But in its case the `bmiColors` member is defined as array of 1 element instead of 0. – i486 Dec 17 '15 at 10:37
  • @i486 In C you would use flexible array members. In C++ it is not possible. – Lundin Dec 17 '15 at 10:38
  • @Lundin The duplicate question is not exactly the same - it is for local array of 0 elements. My question is for array in structure which is special case. – i486 Dec 17 '15 at 10:39
  • @i486 [This](http://stackoverflow.com/questions/17344745/how-to-use-flexible-array-in-c-to-keep-several-values) might be a better duplicate. – Lundin Dec 17 '15 at 10:40

2 Answers2

2

GCC allows zero length arrays as a last member of an struct.
ISO C99 changed this with flexible array member

typedef struct _my_str
{
  int    len;
  double total;
  double tax;
  int    items;
  double item_price[]; // Flexible array member
} my_struct;  

Note that this is not valid in C++ though.

haccks
  • 100,941
  • 24
  • 163
  • 252
2
  1. In C you can use a variable array member but only as the last element of a struct: so in your case you can use double item_price[]; as the final struct element. But note that such a struct cannot be a member of another struct; not even as the final member.

  2. In C++ it is not legal in any circumstance. But alternatives such as std::vector and std::array are adequate.

Bathsheba
  • 227,678
  • 33
  • 352
  • 470
  • 1
    `std:array` doesn't do anything useful for this situation and `std::vector` adds overhead compared to a pointer to dynamic array, when the whole point of this C idiom is to remove overhead compared to a pointer to dynamic array. – JSF Dec 17 '15 at 10:39