I noticed that when compiled with GCC 4.6 sizeof(Foo)
is 0 and sizeof(Bar)
is 1. For some reason adding an empty array into an empty structure made its size 0. I thought that the sizes of both structures must be the same. What is going on here?
struct Foo
{
char x[];
};
struct Bar {};
Neither struct
declaration is allowed by the C standard. 6.7.2.1 (8) in n1570:
If the struct-declaration-list does not contain any named members, either directly or via an anonymous structure or anonymous union, the behavior is undefined.
And paragraph 18 in the same section:
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 most situations, the flexible array member is ignored. In particular, the size of the structure is as if the flexible array member were omitted except that it may have more trailing padding than the omission would imply.
(emphasis mine)
Flexible array members are not allowed in C++, so the code is not valid C++ either.
As it is not valid code, the values reported by sizeof
for these are meaningless.
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