为什么不和sizeof为等于每个成员的sizeof的总和一个结构? [英] Why isn't sizeof for a struct equal to the sum of sizeof of each member?

查看:131
本文介绍了为什么不和sizeof为等于每个成员的sizeof的总和一个结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么的sizeof运算符返回结构的结构成员的总大小比大小?

Why does the 'sizeof' operator return a size larger for a structure than the total sizes of the structure's members?

推荐答案

这是因为填充的加入满足对齐约束。 数据结构调整影响性能和方案的正确性:

This is because of padding added to satisfy alignment constraints. Data structure alignment impacts both performance and correctness of programs:


  • 未对齐的访问可能是一个严重的错误(通常 SIGBUS )。

  • 未对齐的访问可能是软错误。

    • 在硬件或予以纠正,对于适度的性能下降。

    • 或者通过在软件中仿真纠正,对严重的性能下降。

    • 在此外,原子和其他并发担保可能被打破,从而导致微妙的错误。

    下面是一个使用典型设置为x86处理器(全部采用32位和64位模式下)一个例子:

    Here's an example using typical settings for an x86 processor (all used 32 and 64 bit modes):

    struct X
    {
        short s; /* 2 bytes */
                 /* 2 padding bytes */
        int   i; /* 4 bytes */
        char  c; /* 1 byte */
                 /* 3 padding bytes */
    };
    
    struct Y
    {
        int   i; /* 4 bytes */
        char  c; /* 1 byte */
                 /* 1 padding byte */
        short s; /* 2 bytes */
    };
    
    struct Z
    {
        int   i; /* 4 bytes */
        short s; /* 2 bytes */
        char  c; /* 1 byte */
                 /* 1 padding byte */
    };
    
    const int sizeX = sizeof(X); /* = 12 */
    const int sizeY = sizeof(Y); /* = 8 */
    const int sizeZ = sizeof(Z); /* = 8 */
    

    一个可以通过对准排序部件(按大小排序为,在基本类型就足够了)(如在实施例结构以Z 上文)最小化的结构的尺寸。

    One can minimize the size of structures by sorting members by alignment (sorting by size suffices for that in basic types) (like structure Z in the example above).

    重要提示:无论是C和C ++标准规定,结构调整是实现定义的。因此每个编译器可以选择不同的方式对齐数据,产生不同的和不兼容的数据布局。对于这个原因,将由不同的编译器使用库打交道时,一定要了解编译器如何对齐数据是非常重要的。一些编译器有命令行设置和/或特殊的#pragma 语句来改变结构对齐设置。

    IMPORTANT NOTE: Both the C and C++ standards state that structure alignment is implementation-defined. Therefore each compiler may choose to align data differently, resulting in different and incompatible data layouts. For this reason, when dealing with libraries that will be used by different compilers, it is important to understand how the compilers align data. Some compilers have command-line settings and/or special #pragma statements to change the structure alignment settings.

    这篇关于为什么不和sizeof为等于每个成员的sizeof的总和一个结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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