I tried to convert something from using the struct hack to using a flexible array member, only to run into the following error message:
error: invalid use of structure with flexible array member
(GCC 4.8.1, gnu99, MinGW)
After trying to track down the cause of the message, I distilled it down to the following relatively-minimal case:
struct a {
union {
struct {
int b;
int c[];
} d;
} e;
};
In other words, a struct with a flexible array member doesn't see to be able to be put inside a union in a struct, even if the union is the last member of the struct.
(Note that putting a flexible array member directly inside the union does seem to work.)
Now: is there any good way to work around this besides reverting back to the struct hack (declaring c as an array of length 1)? A pointer to a struct inside the union would work, but suffers an additional layer of indirection.
An array in a structure is declared with an initial size. You cannot initialize any structure element, and declaring an array size is one form of initialization.
Flexible array members are a special type of array in which the last element of a structure with more than one named member has an incomplete array type; that is, the size of the array is not specified explicitly within the structure.
The C11 standard (ISO/IEC 9899:2011) says:
§6.7.2.1 Structure and union specifiers
¶18 As a special case, the last element of a structure with more than one named member may have an incomplete array type; this is called a flexible array member.
In the example you have, the last member of struct a
is not a flexible array member. It is a union
containing a struct
that has a flexible array member.
You have to work quite hard to get gcc
to complain, though; it requires -pedantic
amongst the compiler options.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With