I want to declare a struct with a flexible array member in it, and then use sizeof()
on it. The prototype is:
typedef struct
{
uint16_t length;
uint8_t array[][2];
} FLEXIBLE_t;
I then declare it:
const FLEXIBLE_t test = {
.length = sizeof(test),
.array = { { 0, 1 },
{ 2, 3 },
{ 4, 5 },
{ 6, 7 },
{ 8, 9 } }
};
Everything compiles okay (GCC) but when I examine test.length
it has the value 2, i.e. it is only counting the uint16_t
for length
itself.
How can I calculate the size of the struct at compile time? It appears that the compiler uses the prototype rather than the specific instance.
test
is defined inside a function without thestatic
qualifier (const
is not material), then GCC does not allow the initialization of a structure with a flexible array member (FAM). If the variable has file scope or is markedstatic
, then GCC, as an extension, allows the initialization. – Dekameter.length
assignment after the array. But see comments for more formal notes. – Proto