Search code examples
c++arraysstructg++flexible-array-member

Run-time sized array in a c++ struct


In C (with gcc), I used to have some data structures that were an array with some extra information:

struct song {
    uint tempo;
    uint key;
    note play[0]; // or play[] depending on compiler flavour
};

Iirc, that's dubbed a "flexible array" (http://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html#Zero-Length) I could then allocate a song of N notes with malloc(sizeof(song)+N*sizeof(note)) at run-time. To what extent is that supported in g++, if I don't intend to use vectors this time, nor to introduce a useless note* pointer in song ?


Solution

  • Even in C, this is undefined and non-portable. GCC knowingly lets you get away with it, but other implementations may not. This is because you are accessing an array beyond its bounds.

    This "trick" is precisely as valid in C++ as it is in C. That is, feel free to use it in GCC where the GCC documentation says it's supported, but it'll never be "well-defined, valid C++".