One element array in struct

arrays, element, struct

Solution

In a word, yes.

Basically, the C99 way to do it is with an flexible array member:

uint32 words[];

Some pre-C99 compilers let you get away with:

uint32 words[0];

But the way to guarantee it to work across all compilers is:

uint32 words[1];

And then, no matter how it's declared, you can allocate the object with:

Bitmapset *allocate(int n)
{
    Bitmapset *p = malloc(offsetof(Bitmapset, words) + n * sizeof(p->words[0]));
    p->nwords = n;
    return p;
}

Though for best results you should use `size_t` instead of `int`.

Problem

Why some struct uses a single element array, such as follows: ``` typedef struct Bitmapset { int nwords; uint32 words[1]; } Bitmapset; ``` To make it convenient for latter dynamic allocation?

Original source