ℙℕℤℝ 2008-09-23 04:24
浏览 383
已采纳

为什么结构体的 sizeof 不等于每个成员 sizeof 的总和?

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

转载于:https://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member

  • 写回答

11条回答 默认 最新

  • Memor.の 2008-09-23 04:25
    关注

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

    • Mis-aligned access might be a hard error (often SIGBUS).
    • Mis-aligned access might be a soft error.
      • Either corrected in hardware, for a modest performance-degradation.
      • Or corrected by emulation in software, for a severe performance-degradation.
      • In addition, atomicity and other concurrency-guarantees might be broken, leading to subtle errors.

    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(struct X); /* = 12 */
    const int sizeY = sizeof(struct Y); /* = 8 */
    const int sizeZ = sizeof(struct Z); /* = 8 */
    

    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).

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(10条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置