0

I tried declaring an array a of size 0:

int a[0]; 

My VC++ 6 compiler throws an error of not being able to create an array of zero size.

If I try the same of declaring inside a structure, I do not get any errors.

struct st
{
    int a[0];
}

The code gets compiled and linked without any errors. Can somebody help me understand how the compiler reacts in the above two cases. Thanks.

Luca Geretti
  • 10,206
  • 7
  • 48
  • 58
rajez79
  • 123
  • 3

2 Answers2

4

The struct is a special case. It is a common pattern to declare an empty array as the last member of a struct, where the struct is actually part of a larger block of memory of variable length. See Empty arrays in structs for more explanation.

Graham Borland
  • 60,055
  • 21
  • 138
  • 179
0

Some compilers support the extension of using zero-sized arrays as the last element of the struct, to indicate your intent to allocate there an array whose size you don't know yet. Then you can use that struct member (the zero-sized array) to access the elements of that array.

Note that is not an standard feature from C89, and C99 offers an alternative solution:

struct st
{
    int a[];
}
lvella
  • 12,754
  • 11
  • 54
  • 106