2

I just came across some code which declares a struct within a C++ class as follows:

struct T 
{
       int data;
       T* next;
} array[0];

What does this kind of declaration do? What effect does putting "array[0]" at the end of the struct defintion have?

Rohit
  • 7,449
  • 9
  • 45
  • 55

6 Answers6

3

Ahh, it's almost a "flexible array member".

It was formalized in C99, but it's an old C trick that creates a dynamic array. Allocate more memory for the object and you can store more elements in the array.

I think the use of a specific 0 there is a compromise, as actual [] flexible arrays were not in C89 or C++. The more canonical legacy use of this pattern is ...[1].

DigitalRoss
  • 143,651
  • 25
  • 248
  • 329
1

This means, the struct definition is available only within that class.

Shamim Hafiz - MSFT
  • 21,454
  • 43
  • 116
  • 176
  • Thanks. More specifically I wanted to know what effect does putting "array[0]" at the end have? – Rohit Jan 24 '11 at 08:03
1

It's an attempt to declare a type, T and an array of size zero of T. However, it is not legal to declare a zero sized array in C++. The code is not valid.

CB Bailey
  • 755,051
  • 104
  • 632
  • 656
1

In some compilers like GCC a zero length array is a synonym for a flexible class/struct member declared using the [] notation.

thkala
  • 84,049
  • 23
  • 157
  • 201
0

Not sure if it's the case, but:

When a structure have to contain a variable length C string (that won't change after initialization), then instead of writing:

struct x {
    int key;
    const char* s;
};

when we'll need two malloc's (one for struct, and one for string), we can write

struct X2 {
    int key;
    char s[1];
}x2;
// and use it like 
x2* tmp = (x2*)malloc(sizeof(x2) + strlen(str));

Here we have only one malloc for both, structure and the string.

When the last atribute of a structure is an array, then by allocating variable space for the structure we can allocate it with variable number of such members. I think this happens in your case.

ruslik
  • 14,714
  • 1
  • 39
  • 40
0

It is well known as c struct hack, but take care when you use it

Community
  • 1
  • 1
BЈовић
  • 62,405
  • 41
  • 173
  • 273