Zero size struct

匿名 (未验证) 提交于 2019-12-03 02:24:01

问题:

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.



文章来源: Zero size struct
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!