Format of Unaligned or Packed Structures

The C++ compiler may generate extra fields for classes that contain base classes or virtual functions. Objects of these types may not conform to the mapping shown below.

Type The definition of the structure variable is preceded by the #pragma pack directive or the keyword _Packed in C, or the /Sp compiler option is used. For example, the following lines define a packed struct called mystruct
#pragma pack(1);
   struct mystruct {
   char char1;
   short short1; 
   char char2;
   float float1;
   char char3;
}; 
Size The sum of the sizes of each type that makes up the struct.
Storage
Mapping
When the _Packed keyword, the #pragma pack(1) directive, or /Sp1 option is used, the structure mystruct is stored as shown below.

High memory is to the right.

byte 0 byte 1 byte 2 byte 3 byte 4
char1 short1 short1 char2 float1
byte 5 byte 6 byte 7 byte 8  
float1 float1 float1 char3  

When #pragma pack(2) or the /Sp2 option is used, mystruct is stored as shown below:

byte 0 byte 1 byte 2 byte 3 byte 4 byte 5
char1 pad short1 short2 char2 pad
byte 6 byte 7 byte 8 byte 9 byte 10 byte 11
float1 float1 float1 float1 char3 pad


Data Mapping


Summary of Compiler Options
Keywords in C and C++