【问题标题】:sizeof empty structure is 0 in C and 1 in C++ why? [duplicate]sizeof 空结构在 C 中为 0,在 C++ 中为 1,为什么? [复制]
【发布时间】:2010-10-03 10:10:01
【问题描述】:

可能的重复:
Empty class in C++
What is the size of an empty struct in C?

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

意思是

struct Empty {

};

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

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

【问题讨论】:

  • -1 不,您没有将其编译为C
  • @Ninad:你试过this吗?
  • 当您在此语言级别提问时,请提供编译器名称和版本。
  • 这是一个超级副本。对于 C,this 的副本(答案:格式不正确)。在 C++ 中,this(答案:它的大小必须大于零,以便为其分配空间)。
  • -1 我也是。 sizeof 无法编译

标签: c++ c struct sizeof


【解决方案1】:

C 中不能有空结构。这是违反句法约束的。 但是 gcc 允许在 C as an extension 中使用空结构。 此外,如果结构没有任何命名成员,则行为是 undefined,因为

C99 说:

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

所以

struct Empty {}; //constraint violation

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

是的,空结构的大小是 C++ cannot be zero :)

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2012-08-27
        • 1970-01-01
        • 2018-03-05
        • 1970-01-01
        • 2011-03-09
        • 2012-01-29
        • 2021-05-25
        • 2021-07-02
        • 1970-01-01
        相关资源
        最近更新 更多