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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3849334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 13:53:28  来源:igfitidea点击:

sizeof empty structure is 0 in C and 1 in C++ why?

c++cstructsizeof

提问by Ninad Page

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

可能的重复项:
C++ 中的空类 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.

我在某处读到 C++ 中空结构的大小是 1。所以我想验证它。不幸的是,我将它保存为 C 文件并使用了<stdio.h>标头,我很惊讶地看到输出。它是 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 two objects of the class would have the same address which is not possible. Where am I wrong?

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

回答by Prasoon Saurav

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 undefinedif the structure does not have any named member because

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

C99says :

C99说:

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

如果 struct-declaration-list 不包含命名成员,则行为未定义。

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:)

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

回答by vog

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://bytes.com/topic/c/insights/660463-sizeof-empty-class-structure-1-a

回答by Necrolis

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

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

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

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