为什么'sizeof'给出错误的测量值?
可能的重复:
结构 sizeof 结果不是预期的
我有这个 C++ 结构:
struct bmp_header {
//bitmap file header (14 bytes)
char Sign1,Sign2; //2
unsigned int File_Size; //4
unsigned int Reserved_Dword; //4
unsigned int Data_Offset; //4
//bitmap info header (16 bytes)
unsigned int Dib_Info_Size; //4
unsigned int Image_Width; //4
unsigned int Image_Height; //4
unsigned short Planes; //2
unsigned short Bits; //2
};
它应该是 30 个字节,但是 'sizeof(bmp_header)' 给我的值为 32。出了什么问题?
Possible Duplicate:
struct sizeof result not expected
I have this C++ struct:
struct bmp_header {
//bitmap file header (14 bytes)
char Sign1,Sign2; //2
unsigned int File_Size; //4
unsigned int Reserved_Dword; //4
unsigned int Data_Offset; //4
//bitmap info header (16 bytes)
unsigned int Dib_Info_Size; //4
unsigned int Image_Width; //4
unsigned int Image_Height; //4
unsigned short Planes; //2
unsigned short Bits; //2
};
It is supposed to be 30 bytes, but 'sizeof(bmp_header)' gives me value 32. What's wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它不会给出错误的测量结果。您需要了解对齐和填充。
编译器可以在结构成员之间添加填充以遵守对齐约束。也就是说,可以使用编译器特定指令来控制填充(请参阅 GCC 变量属性 或 MSVC++编译指示)。
It doesn't give a wrong measurement. You need to learn about alignment and padding.
The compiler can add padding in between structure members to respect alignment constraints. That said, it's possible to control padding with compiler specific directives (see GCC variable attributes or MSVC++ pragmas).
原因是因为填充。如果将
char
放在结构的末尾,sizeof
可能会给您 30 个字节。整数一般存储在4的倍数的内存地址上。因此,由于chars占用2个字节,因此它和第一个unsigned int之间有两个未使用的字节。与int
不同,char
通常不进行填充。一般来说,如果空间是一个大问题,请始终将结构体元素从最大到最小排序。
请注意,填充并不总是(或通常)是
sizeof(element)
。int
按 4 个字节对齐,而char
按 1 个字节对齐,这是一个巧合。The reason is because of padding. If you put the
char
s at the end of the struct,sizeof
will probably give you 30 bytes. Integers are generally stored on memory addresses that are multiples of 4. Therefore, since the chars take up 2 bytes, there are two unused bytes between it and the first unsigned int.char
, unlikeint
, is not usually padded.In general, if space is a big concern, always order elements of
structs
from largest in size to smallest.Note that padding is NOT always (or usually) the
sizeof(element)
. It is a coincidence thatint
is aligned on 4 bytes andchar
is aligned on 1 byte.2+2+4+4+4+4+4+4+2+2 = 32。对我来说看起来是正确的。如果您期望 30,则意味着您期望 1 字节填充,如下所示:
2+2+4+4+4+4+4+4+2+2 = 32. Looks correct to me. If you expect 30 it means you expect 1 byte padding, as in :