0

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 ?

PypeBros
  • 2,607
  • 24
  • 37

2 Answers2

4

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++".

Community
  • 1
  • 1
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • 2
    I vaguely remember that there was actually a pretty huge bug in some widely used OSS app due to reliance of out-of-bound pointer access. This may *seem* safe but it most decidedly is not, and the optimiser can pull some very funky stunts that render such code dangerous. – Konrad Rudolph Feb 17 '13 at 13:45
-1

there is no other way than using a fixed length or a note* because the compiler must know how long your song-structs are, and every struct has the same lenght.

so you have to use a note* or a vector

El Hocko
  • 2,581
  • 1
  • 13
  • 22