Why does 'sizeof' give wrong measurement? [duplicate]

Deadly 提交于 2019-12-19 07:39:09

问题


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?


回答1:


The reason is because of padding. If you put the chars 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.

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 that int is aligned on 4 bytes and char is aligned on 1 byte.




回答2:


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).




回答3:


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. Looks correct to me. If you expect 30 it means you expect 1 byte padding, as in :

#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)


来源:https://stackoverflow.com/questions/7351654/why-does-sizeof-give-wrong-measurement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!