简体   繁体   English

填充如何在结构中工作?

[英]how does padding work in structure?

The output of this program is 28. I don't understand how? 这个程序的输出是28.我不明白怎么办? According to me this should be 32(4+4+4+4+12)+4(to maintain the alignment)=32. 据我说,这应该是32(4 + 4 + 4 + 4 + 12)+4(保持对齐)= 32。 Please explain the reason for displaying the output 28?? 请解释显示输出的原因28 ??

struct test{
    char c;
    int d;
    int x;
    int y;
    long double p;
    }t1;

printf("%d",sizeof(t1));

Maybe your "long double" is actually the same as a double (8 bytes), and if you're on a 32bit processor the alignment is 4-byte. 也许你的“long double”实际上与double(8字节)相同,如果你在32位处理器上,则对齐是4字节。

4+4+4+4+8 = 24 4 + 4 + 4 + 4 + 8 = 24

What is sizeof(long double) ? 什么是sizeof(long double)

EDIT: 编辑:

I used GCC's __builtin_offset_of() and __alignof__ to investigate. 我使用GCC的__builtin_offset_of()__alignof__进行调查。 The actual answer that explains the size of the struct is: 解释结构大小的实际答案是:

4+4+4+4+12 = 28 4 + 4 + 4 + 4 + 12 = 28

sizeof(long double) is 12. sizeof(long double)是12。

No padding is necessary because __alignof__(long double) is 4 and. 不需要填充,因为__alignof__(long double)是4和。 Interestingly, __alignof__(double) is 8. 有趣的是, __alignof__(double)是8。

On a 64 bit system sizes are char - 1 byte(its not 4 bytes) int - 4 bytes long double - 12 bytes 在64位系统上,字符大小为char - 1字节(不是4字节)int - 4字节长双--12字节

so total is 1+4+4+4+12+padding = 28 bytes!! 所以总数是1 + 4 + 4 + 4 + 12 +填充= 28个字节!!

According to this , long doubles in gcc 32-bit mode (using gcc -m32 or with a gcc that was built to produce 32-bit output, regardless of what your platform actually is) are only 4-byte aligned. 根据这一点 ,gcc 32位模式中的长双精度(使用gcc -m32或用于生成32位输出的gcc,无论你的平台实际是什么)都只有4字节对齐。 Might be good to consult the gcc manual to verify that, though. 不过,可以参考gcc手册来验证这一点。

That seems right to me. 这似乎对我来说。 A field immediately following p would be 4-byte aligned, so there's no need for padding at the end of the structure. 紧跟在p之后的字段将是4字节对齐的,因此在结构的末尾不需要填充。

4+4+4+4+12=28 4 + 4 + 4 + 4 + 12 = 28

On my system, the output is 32, but on my system, sizeof(long double) is 16. (x86_64, LLVM3). 在我的系统上,输出是32,但在我的系统上,sizeof(long double)是16.(x86_64,LLVM3)。

The 28 sizeof output is of course correct = 1 byte for char, 3 bytes padding, 3 x 4 int and 12 bytes for long double (96 bits size but 80 bit precision), which makes in total 28 bytes. 28 sizeof输出当然是正确的= 1字节用于char,3字节填充,3 x 4 int和12字节用于long double(96位大小但80位精度),这使得总共28个字节。

Remember that even tho you compile on x86-64 machine, you probably compile for x86-32 machine using mingw32 and that makes a difference. 请记住,即使你在x86-64机器上编译,你可能使用mingw32为x86-32机器编译,这也有所不同。

Mingw32 uses 4 byte allignement for long double . Mingw32使用4字节的allignement为long double

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM