假设我有一个结构为:
struct simple_struct_1
{
long long a;
char b;
long c;
};
a的地址是:0x7ffd415c8b20
b 的地址是:0x7ffd415c8b28
c 的地址是:0x7ffd415c8b30
simple_struct_1
的大小是 24
我已经打印了每个成员的地址和结构的大小,我如何显示这个结构在内存中是如何放置的?就像在 simple_struct_1
中,a
占用 111 个字节并有 222 个填充字节,之后 b
占用 333 个字节,其后有 0 个填充字节,并且c
占用 444 字节,其后填充 555 字节。
最佳答案
您可以使用 offsetof
和 sizeof
获取每个单独字段的详细信息以及整个结构的大小,例如:
printf ("a is %d@%d\n", sizeof(simple_struct_1.a), offsetof(simple_struct_1, a));
printf ("b is %d@%d\n", sizeof(simple_struct_1.b), offsetof(simple_struct_1, b));
printf ("c is %d@%d\n", sizeof(simple_struct_1.c), offsetof(simple_struct_1, c));
printf ("struct is %d@0\n", sizeof(simple_struct_1));
这应该能让你锻炼:
- 所有字段的偏移量和大小;
- 字段之间的间隙;和
- 最后一个字段之后的间隙(将其偏移量和大小与整个结构的大小相结合。
不要担心在第一个字段之前填充,ISO 标准禁止这样做。
例如,假设您在左侧看到以下输出,右侧显示尺寸和间隙:
a is 16@0 16 bytes for a long long
no gap (0 + 16 = 16, next at 16)
b is 1@16 1 byte for a char
7 bytes gap (16 + 1 = 17, next at 24)
c is 8@24 8 bytes for a long
struct is 32@0 no gap at end (24 + 8 = 32, next at 32)
关于c - 如何计算结构成员和填充的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46009855/