为什么'sizeof'会给错误的测量?

时间:2011-09-08 16:49:32

标签: c++ struct sizeof

  

可能重复:
  struct sizeof result not expected

我有这个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.什么错了?

3 个答案:

答案 0 :(得分:9)

它没有给出错误的测量结果。您需要了解alignment and padding

编译器可以在结构成员之间添加填充以遵守对齐约束。也就是说,可以使用编译器特定的指令来控制填充(请参阅GCC variable attributesMSVC++ pragmas)。

答案 1 :(得分:6)

原因是因为填充。如果将char放在结构的末尾,sizeof可能会给你30个字节。整数通常存储在4的倍数的存储器地址中。因此,由于字符占用2个字节,因此它与第一个unsigned int之间有两个未使用的字节。与char不同,int通常不会填充。

一般来说,如果空间是一个大问题,请始终将structs的元素从最大尺寸排序到最小。

请注意,填充并不总是(或通常)sizeof(element)重合int在4个字节上对齐,char在1个字节上对齐。

答案 2 :(得分:2)

struct bmp_header {

  char Sign1,Sign2; //2
  // padding for 4 byte alignment of int: // 2
  unsigned int File_Size; //4
  unsigned int Reserved_Dword; //4
  unsigned int Data_Offset; //4

  unsigned int Dib_Info_Size; //4
  unsigned int Image_Width; //4
  unsigned int Image_Height; //4

  unsigned short Planes; //2
  unsigned short Bits; //2  
};

2 + 2 + 4 + 4 + 4 + 4 + 4 + 4 + 2 + 2 = 32.看起来对我不对。如果你期望30意味着你期望1字节填充,如:

#pragma pack(push)
#pragma pack(1)

struct bmp_header {

  char Sign1,Sign2; //2
  unsigned int File_Size; //4
  unsigned int Reserved_Dword; //4
  unsigned int Data_Offset; //4

  unsigned int Dib_Info_Size; //4
  unsigned int Image_Width; //4
  unsigned int Image_Height; //4

  unsigned short Planes; //2
  unsigned short Bits; //2  
};

#pragma pack(pop)
相关问题