空结构体的 sizeof 在 C 中为 0,在 C++ 中为 1为什么?
可能的重复:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
C 中不能有空结构。这是违反语法约束的。
然而,gcc 允许 C 中的空结构作为扩展。
此外,如果结构没有任何命名成员,则行为是未定义,因为
C99
说:所以
,是的,空结构的大小是 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 :So
And yes size of an empty struct is C++ cannot be zero :)
有几个很好的理由。其中,这是为了确保指向该结构的指针的指针算术不会导致无限循环。更多信息:
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
这是一篇精彩的文章,描述了为什么会发生这种情况,更相关的是,解决它的(安全)方法:)
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