Why can't I have flexible array members in union? Consider this:
struct foo {
enum { t_char, t_int, t_ptr, /* .. */ } type;
int count;
union {
char c[];
int i[];
void *p[];
/* .. */
};
};
This isn't allowed, since flexible array members are only allowed in structs (but the union here is exactly where you'd put a flexible array member if you had only one type to deal with).
Furthermore, you can't work around this by wrapping the union's members in a struct because they must have more than one named member:
struct foo {
enum { t_char, t_int, t_ptr } type;
int count;
union { /* not allowed! */
struct { char c[]; };
struct { int i[]; };
struct { void *p[]; };
};
};
But it's all fine if we either add a useless dummy variable or move some prior member (such as count) into these structs:
struct foo {
enum { t_char, t_int, t_ptr } type;
int count;
union { /* this works but is silly and redundant */
struct { int dumb1; char c[]; };
struct { int dumb2; int i[]; };
struct { int dumb3; void *p[]; };
};
};
Of course, you could have the last member be
union { char c; int i; void *p; } u[];
but then each element of u is as large as the largest possible member which is wasteful, and u can't be passed to any function that expects to get a normal, tightly packed array of one specific type.
Furthermore, you can't work around this by wrapping the union's members in a struct because they must have more than one named member:
But it's all fine if we either add a useless dummy variable or move some prior member (such as count) into these structs: Of course, you could have the last member be but then each element of u is as large as the largest possible member which is wasteful, and u can't be passed to any function that expects to get a normal, tightly packed array of one specific type.