Can someone explain why this doesn’t work? Below is a simple example of what I’m trying to do. I don’t need an explanation on error: flexible array member
. I understand that if int g[]
is not at the end of the struct, there is ambiguity about the size of the struct that needs to be allocated. In my mind though, creating a union with a particular size seems to get around this. The union here is 100 bytes, so if I use the union, then there shouldn’t be ambiguity about the structs size.
My expectation is that the struct S
, by default will be evaluated as 204
bytes.
I’m dealing with this problem because I’m using some C code in a C++ project. When the C code is compiled in a C context, this code compiles and works as I’ve described. But in C++, I get the error: flexible array member
error.
I’m trying to explore all options before refactoring the C code and I’m trying to understand why the C++ compiler doesn’t allow this while the C compiler does.
struct A {
int a;
int b;
int c;
};
struct B {
int d;
int e;
int f;
int g[];
};
union U {
B b;
A a;
uint8_t arr[100];
};
struct S {
int b;
U u1;
U u2;
};
int main()
{
U u = {{0}};
S s = {0};
printf("size=%lun", sizeof(U));
return 0;
}
error
error: flexible array member ‘B::g’ not at end of ‘struct S’
5