我在 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 -> 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 字节对齐。
- 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.114 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/