C99 supports something called a "flexible" array element, which is allowed to be the last member of the structure. When you dynamically allocate such a structure, you can increase the requested amount from malloc() to provide memory for the array.
Some compilers add this as an extension to C90 and / or C ++.
So you can have the following code:
struct foo_t { int x; char buf[]; }; void use_foo(size_t bufSize) { struct foo_t* p = malloc( sizeof( struct foo_t) + bufSize); int i; for (i = 0; i < bufSize; ++i) { p->buf[i] = i; } }
You cannot define a structure with a flexible array element directly (as a local or global / static variable), because the compiler will not know how much memory is allocated for it.
I honestly don't know how you can easily use such a thing with the C ++ new operator - I think you will need to allocate memory for the object using malloc() and use the new location. Perhaps you can use some operator new type overloading for the class / structure ...
Michael burr
source share