C中空结构的大小是多少? [英] What is the size of an empty struct in C?

查看:20
本文介绍了C中空结构的大小是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,它为零,但似乎有点混乱 这里

According to me, it is zero but there seems to be bit confusion here

我已经用 gcc 编译器对其进行了测试,它给了我零作为输出.我知道在 C++ 中,空类的大小是 1.如果我在这里遗漏了什么,请告诉我.

I have tested it with gcc compiler and it gives me zero as output. I know that in C++, size of an empty class is 1. Let me know if I am missing anything here.

推荐答案

C 中的结构不能为空,因为语法禁止它.此外,如果结构没有命名成员,则存在语义约束使行为未定义:

A struct cannot be empty in C because the syntax forbids it. Furthermore, there is a semantic constraint that makes behavior undefined if a struct has no named member:

struct-or-union-specifier:
  struct-or-union identifieropt { struct-declaration-list }
  struct-or-union identifier

struct-or-union:
  struct
  union

struct-declaration-list:
  struct-declaration
  struct-declaration-list struct-declaration

struct-declaration:
  specifier-qualifier-list struct-declarator-list ;

/* type-specifier or qualifier required here! */
specifier-qualifier-list:
  type-specifier specifier-qualifier-listopt
  type-qualifier specifier-qualifier-listopt

struct-declarator-list:
  struct-declarator
  struct-declarator-list , struct-declarator

struct-declarator:
  declarator
  declaratoropt : constant-expression

如果你写

struct identifier { };

它会给你一个诊断信息,因为你违反了句法规则.如果你写

It will give you a diagnostic message, because you violate syntactic rules. If you write

struct identifier { int : 0; };

然后你有一个没有命名成员的非空结构,从而使行为未定义,并且不需要诊断:

Then you have a non-empty struct with no named members, thus making behavior undefined, and not requiring a diagnostic:

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

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

注意以下是不允许的,因为灵活的数组成员不能是第一个成员:

Notice that the following is disallowed because a flexible array member cannot be the first member:

struct identifier { type ident[]; };

这篇关于C中空结构的大小是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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