可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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 {};
回答1:
Neither struct
declaration is allowed by the C standard. 6.7.2.1 (8) in n1570:
And paragraph 18 in the same section:
As a special case, the last element of a structure with more than one named member
(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.
回答2:
The sizeof operator never yields 0, even for an empty class.
as you can see here on msdn
furthermore the msdn is stating:
The sizeof operator cannot be used with the following operands:
- Functions. (However, sizeof can be applied to pointers to functions.)
- Bit fields.
- Undefined classes.
- The type void.
- Dynamically allocated arrays.
- External arrays.
- Incomplete types.
- Parenthesized names of incomplete types.
回答3:
C and C++ do not permit zero-sized objects.
gcc does support them as an extension. If you compile with the proper options, such as
gcc -std=c99 -pedantic -Wall -Wextra
gcc will at least warn you about them; g++ has similar options.