c - 嵌套结构填充 - C - 64 位 - linux

标签 c 64-bit nested padding structure

我在 C 中有以下嵌套结构。(64 位)

    typedef struct {
        int a;
        int b;
        int c;
        struct {
            int ab;
            long bc;
        }
        int d;
    } Test;

I see that,
a = 4 bytes
b = 4 bytes
c = 4 bytes
padding1 = 4 bytes 
inner structure = 16 bytes ( 4 bytes for ab, 4 bytes padding, 8 bytes for bc)
d = 4 bytes
padding2 = 4 bytes

sizeof(Test) 返回 40 个字节。

我的问题:
  • padding1 -> 为什么是 4 个字节?这是因为内部结构本身应该对齐吗?。 (另外,它是否与 8 字节(长)或 16 字节(内部大小)边界对齐。?)
  • padding2 -> 这是 4 字节的填充,因为在结构内部完成了最大对齐(8 位)??

  • 谢谢,

    最佳答案

    1. padding1 -> why is this 4 bytes? Is this because the inner structure itself should be aligned ?. ( Also, Is it aligned with 8 byte (long) or 16 byte (size of inner) boundary.? )


    这是因为内部struct应该是 8 字节对齐的,这样 long可以可靠地进行 8 字节对齐。

    1. padding2 -> Is this 4 byte padding because of max of alignment done inside the structure (which is eight) ??


    它在那里使整个struct的大小是八字节的倍数,所以内部struct可以在八字节边界上适当对齐。

    在这种特殊情况下,如果匿名 struct,只需四个字节的填充就可以满足对齐要求。成员(member)可以与独立成员(member)区别对待 struct ,但 6.7.2.1

    14 Each non-bit-field member of a structure or union object is aligned in an implementation-defined manner appropriate to its type.



    禁止这样做。所以要减小struct的大小,程序员需要重新排列,移动奇数int成员(member)过去内struct (或让 int ab;long bc; 成为 Test 的直接成员,而无需通过匿名 struct )。

    关于c - 嵌套结构填充 - C - 64 位 - linux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13927378/

    相关文章:

    c - 如何在线程中共享内存

    c# - 了解平台目标

    linux - 嵌套的 if/then/elseif 在 bash 中如何工作?

    java - 如何遍历嵌套 java 对象列表?

    c - 如何在c中不使用全局变量

    c - 无法更新 c 中给定 char 指针的值

    C - 将值插入到结构中

    ios - iOS 中静态库的 64 位支持

    c# - 使用安装项目在 x64 程序集中调用自定义操作

    c# - 在静态类中实例化嵌套类