- 论坛徽章:
- 0
|
在使用sizeof前,需要了解指令的字节对齐情况
本例中sizeof(BitMapFileHeader)是16而不是14,说明为4字节对齐
常见的字节对齐有1、2、4字节对齐,各种情况分析分别如下:
1字节对齐 变量 内存组织
unsigned short bfType --> 1 byte
unsigned long bfSize --> 4 bytes
unsigned short bfReserved1 --> 1 byte
unsigned short bfReserved2 --> 1 byte
unsigned long bfOffBits --> 4 bytes
sizeof(BitMapFileHeader) = 11 bytes
2字节对齐 变量 内存组织
unsigned short bfType --> 1 byte
--> 1 byte (alignment,字节对齐)
unsigned long bfSize --> 4 bytes
unsigned short bfReserved1 --> 1 byte
unsigned short bfReserved2 --> 1 byte
unsigned long bfOffBits --> 4 bytes
sizeof(BitMapFileHeader) = 12 bytes
4字节对齐 变量 内存组织 (A)
unsigned short bfType --> 1 byte
--> 3 bytes (alignment,字节对齐)
unsigned long bfSize --> 4 bytes
unsigned short bfReserved1 --> 1 byte
unsigned short bfReserved2 --> 1 byte
--> 2 bytes (alignment,字节对齐)
unsigned long bfOffBits --> 4 bytes
sizeof(BitMapFileHeader) = 16 bytes
通过上述各种情况的分析,可以发现:合理的组织成员变量,可以达到内存的最大利用
4字节对齐为例,如:
1字节对齐 变量 内存组织 (B)
unsigned long bfSize --> 4 bytes
unsigned short bfType --> 1 byte
unsigned short bfReserved1 --> 1 byte
unsigned short bfReserved2 --> 1 byte
--> 1 byte (alignment,字节对齐)
unsigned long bfOffBits --> 4 bytes
sizeof(BitMapFileHeader) = 12 bytes
比较(A)和(B),(B)相对(A)节省了4个字节的内存空间 |
|