为什么'sizeof'给出错误的测量? [英] Why does 'sizeof' give wrong measurement?
问题描述
可能重复:
struct sizeof结果不期望
我有这个C ++结构:
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
};
它应该是30个字节,但是'sizeof(bmp_header)'给了我32。错误?
It is supposed to be 30 bytes, but 'sizeof(bmp_header)' gives me value 32. What's wrong?
推荐答案
原因是因为填充。如果你把 char
放在结构的末尾, sizeof
可能会给你30个字节。整数通常存储在为4的倍数的存储器地址上。因此,由于字符占用2个字节,所以它与第一个unsigned int之间有两个未使用的字节。与 int
不同, char
通常不填充。
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
, unlike int
, is not usually padded.
一般来说,如果空间是一个很大的问题,请务必将 structs
的元素从大到最小排序。
In general, if space is a big concern, always order elements of structs
from largest in size to smallest.
注意,padding不总是(或通常) sizeof(element)
。这是巧合, int
在4个字节对齐, char
在1字节。
Note that padding is NOT always (or usually) the sizeof(element)
. It is a coincidence that int
is aligned on 4 bytes and char
is aligned on 1 byte.
这篇关于为什么'sizeof'给出错误的测量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!