用C的sizeof内部机制? [英] Internal mechanism of sizeof in C?

查看:122
本文介绍了用C的sizeof内部机制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用sizeof的获得在C结构的大小,但我得到的结果是出人意料的。

 结构sdshdr {
    INT LEN;
    INT免费;
    烧焦BUF [];
};
诠释主(){
    的printf(结构LEN数:%d \\ n,(的sizeof(结构sdshdr)));
    返回0;
} //结构的len:8,有或没有的buf

我的问题是,为什么 BUF 不占用任何空间,为什么的 INT 键入还在4大小在64位CPU?

下面是从输出的gcc -v

 配置有: -  preFIX = /应用/ X code.app /内容/开发/ USR --with-GXX-包括-DIR = / USR /include/c++/4.2.1
(基于LLVM 3.6.0svn)苹果LLVM版本6.1.0(铛-602.0.53)
目标:x86_64的 - 苹果darwin14.4.0
线程模型:POSIX


解决方案

的[]是的灵活的数组成员的。他们不计入该结构的总大小,因为C标准明确是这么说的:

6.7.2.1/18


  

作为一个特例,一个结构的一个以上的命名构件的最后一个元件可
  有一个不完整的数组类型;这就是所谓的灵活数组成员。在大多数情况下,
  柔性阵列构件被忽略。具体地,结构的尺寸是因为如果
  除了灵活的阵列成员被省略,它可能有超过尾随填充
  遗漏意味着


这是由设计故意的,因为灵活的阵列成员的目的是让你来分配结构后动态拖尾的数据。 (当该结构是一个文件头,协议标题等)

<一个href=\"http://stackoverflow.com/questions/17344745/how-to-use-flexible-array-in-c-to-keep-several-values/17345123#17345123\">Example包括关于非标GCC的扩展和老pre-C99结构黑客的讨论。

I use sizeof to get size of a struct in C, but the result I got is unexpected.

struct sdshdr {
    int len;
    int free;
    char buf[];
};


int main(){
    printf("struct len:%d\n",(sizeof(struct sdshdr)));
    return 0;
} //struct len:8, with or without buf

my question is why does buf not occupy any space and why is the size of the int type still 4 on a 64-bit CPU?

here is the output from gcc -v:

Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 6.1.0 (clang-602.0.53) (based on LLVM 3.6.0svn)
Target: x86_64-apple-darwin14.4.0
Thread model: posix  

解决方案

The [] is a flexible array member. They do not count towards the total size of the struct, because the C standard explicitly says so:

6.7.2.1/18

As a special case, the last element of a structure with more than one named member may have an incomplete array type; this is called a flexible array member. In most situations, the flexible array member is ignored. In particular, the size of the structure is as if the flexible array member were omitted except that it may have more trailing padding than the omission would imply.

This is intentional by design, because the purpose of a flexible array member is to allow you to allocate trailing data dynamically after the struct. (When the struct is a file header, protocol header etc.)

Example including discussion about non-standard gcc extensions and the old pre-C99 "struct hack".

这篇关于用C的sizeof内部机制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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