问题描述
可能的重复:
C++ 中的空类
C 中空结构的大小是多少?
我在某处读到 C++ 中空结构的大小是 1.所以我想验证它.不幸的是,我将它保存为 C 文件并使用了 <stdio.h>
标头,我很惊讶地看到输出.是 0.
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.
这意味着
struct Empty {
};
int main(void)
{
printf("%d",(int)sizeof(Empty));
}
在编译为 C 文件时打印 0
,在编译为 C++ 文件时打印 1
.我想知道原因.我读到 C++ 中的 sizeof
空结构不为零,因为如果大小为 0
那么该类的两个对象将具有相同的地址,这是不可能的.我哪里错了?
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?
推荐答案
C 中不能有空结构.这是违反语法约束的.然而,gcc 允许 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
说:
如果结构声明列表不包含命名成员,则行为未定义.
If the struct-declaration-list contains no named members, the behavior is undefined.
所以
struct Empty {}; //constraint violation
struct Empty {int :0 ;}; //no named member, the behaviour is undefined.
是的,空结构的大小是 C++ 不能为零 :)
And yes size of an empty struct is C++ cannot be zero :)
这篇关于sizeof空结构在C中为0,在C++中为1,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!