空结构体的 sizeof 在 C 中为 0,在 C++ 中为 1为什么?

发布于 2024-09-26 05:32:18 字数 757 浏览 9 评论 0原文

可能的重复:
C++ 中的空类
C 中空结构的大小是多少?< /a>

我在某处读到C++中空结构的大小是1。所以我想到验证它。 不幸的是,我将其保存为 C 文件并使用 标头,我很惊讶地看到输出。它是 0。

这意味着

struct Empty {

};

int main(void)
{
  printf("%d",(int)sizeof(Empty));
}

编译为 C 文件时打印 0 ,编译为 C++ 文件时打印 1 。我想知道原因。我读到 C++ 中的 sizeof 空结构不为零,因为如果大小为 0 那么该类的两个对象将具有相同的地址,这是不可能的。我哪里错了?

Possible Duplicates:
Empty class in C++
What is the size of an empty struct in C?

I read somewhere that size of an empty struct in C++ is 1. So I thought of verifying it.
Unfortunately I saved it as a C file and used <stdio.h> header and I was surprised to see the output. It was 0.

That means

struct Empty {

};

int main(void)
{
  printf("%d",(int)sizeof(Empty));
}

was printing 0 when compiled as a C file and 1 when compiled as a C++ file. I want to know the reason. I read that sizeof empty struct in C++ is not zero because if the size were 0 then two objects of the class would have the same address which is not possible. Where am I wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

如梦初醒的夏天 2024-10-03 05:32:19

C 中不能有空结构。这是违反语法约束的。
然而,gcc 允许 C 中的空结构作为扩展
此外,如果结构没有任何命名成员,则行为是未定义,因为

C99说:

如果结构声明列表不包含命名成员,则行为未定义。

所以

struct Empty {}; //constraint violation

struct Empty {int :0 ;}; //no named member, the behaviour is undefined.

,是的,空结构的大小是 C++ 不能为零 :)

You cannot have an empty structure in C. It is a syntactic constraint violation.
However gcc permits an empty structure in C as an extension.
Furthermore the behaviour is undefined if the structure does not have any named member because

C99 says :

If the struct-declaration-list contains no named members, the behavior is undefined.

So

struct Empty {}; //constraint violation

struct Empty {int :0 ;}; //no named member, the behaviour is undefined.

And yes size of an empty struct is C++ cannot be zero :)

风筝有风,海豚有海 2024-10-03 05:32:19

有几个很好的理由。其中,这是为了确保指向该结构的指针的指针算术不会导致无限循环。更多信息:

http://bytes.com /topic/c/insights/660463-sizeof-empty-class-struct-1-a

There are several good reasons. Among others, this is to ensure that pointer arithmetics over pointers to that structure don't lead to an infinite loop. More information:

http://bytes.com/topic/c/insights/660463-sizeof-empty-class-structure-1-a

万劫不复 2024-10-03 05:32:19

这是一篇精彩的文章,描述了为什么会发生这种情况,更相关的是,解决它的(安全)方法:)

http: //www.cantrip.org/emptyopt.html

Here is a wonderful article describing why this occurs, and more pertinently, a (safe) way around it :)

http://www.cantrip.org/emptyopt.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文