There is always a misunderstanding about struct Data Alignment and # pragma pack (n). Here we will make a summary to facilitate future memory.
There are two main rules:
1. structure, union, or class data member. The first one is placed at the offset of 0, and the alignment of each data member is later, the value is determined by the value specified by # pragma pack and the length of the data member. The smaller value is used.
2. The alignment of the overall structure is determined by the maximum data member in the struct and the size of # pragma pack, which is smaller.
The following is the test code:
Cpp Code
# Include <iostream>
Using namespace std;
Struct test
{
Short;
Short B;
Int c;
Char d;
};
# Pragma pack (4)
Struct test2
{
Char;
Short B;
Char c;
};
# Pragma pack ()
Struct s1
{
Short;
Long B;
};
Struct s2
{
Char c;
S1 d;
Long e;
};
# Pragma pack (4)
Struct s3
{
Int;
Char B;
Short c;
Char d;
};
Struct s4
{
Char;
Short B;
Char c;
};
# Pragma pack ()
# Pragma pack (2)
Struct s5
{
Int;
Char B;
Short c;
Char d;
};
# Pragma pack ()
Int main ()
{
Cout <sizeof (test) <endl;
Cout <sizeof (test2) <endl;
Cout <sizeof (s1) <endl;
Cout <sizeof (s2) <endl;
Cout <sizeof (s3) <endl;
Cout <sizeof (s4) <endl;
Cout <sizeof (s5) <endl;
Unsigned int ccc;
Cout <sizeof (ccc) <endl;
}
Author "plussai"