In one C++ open source project, I see this.
struct SomeClass {
...
size_t data_length;
char data[1];
...
}
What are the advantages of doing so rather than using a pointer?
struct SomeClass {
...
size_t data_length;
char* data;
...
}
The only thing I can think of is with the size 1 array version, users aren’t expected to see NULL. Is there anything else?
With this, you don’t have to allocate the memory elsewhere and make the pointer point to that.
The trick is to allocate more memory than
sizeof (SomeClass), and make aSomeClass*point to it. Then the initial memory will be used by yourSomeClassobject, and the remaining memory can be used by thedata. That is, you can sayp->data[0]but alsop->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).