Why use array size 1 instead of pointer?

With this, you don’t have to allocate the memory elsewhere and make the pointer point to that.

  • No extra memory management
  • Accesses to the memory will hit the memory cache (much) more likely

The trick is to allocate more memory than sizeof (SomeClass), and make a SomeClass* point to it. Then the initial memory will be used by your SomeClass object, and the remaining memory can be used by the data. That is, you can say p->data[0] but also p->data[1] and so on up until you hit the end of memory you allocated.

Points can be made that this use results in undefined behavior though, because you declared your array to only have one element, but access it as if it contained more. But real compilers do allow this with the expected meaning because C++ has no alternative syntax to formulate these means (C99 has, it’s called “flexible array member” there).

Leave a Comment