sizeof的空结构的C 0和1的C ++为什么呢? [英] sizeof empty structure is 0 in C and 1 in C++ why?

查看:95
本文介绍了sizeof的空结构的C 0和1的C ++为什么呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能显示的文件:结果
  结果href=\"http://stackoverflow.com/questions/2362097/empty-class-in-c\">空类
  什么是空结构的C中的大小?

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

我读的地方在C ++中的空结构的该尺寸是1。因此,我认为它验证的。
不幸的是我救它作为一个C文件,并使用<&stdio.h中GT; 头,我很惊讶地看到输出。这是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 ++编译文件作为C文件编译和1打印0。我想知道原因。我读,在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 two objects of the class would have the same address which is not possible. Where am I wrong?

推荐答案

您不能有一个空的结构C.这是一个语法约束冲突。
然而海湾合作委员会允许使用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和1的C ++为什么呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆