The Byte alignment problem of struct (example of modifying byte alignment through Pragma pack (n)
# Pragma pack (n) is used to change the byte alignment of the C compiler. In C, the structure is a composite data type, the element can be a variable of the basic data type (such as int, long, float), or a combination of data types (such as array, structure, Union, etc). In the structure, the compiler allocates space for each member of the structure based on its natural alignment condition. See the following example.
The output is:
Sizeof (char) = 1 sizeof (INT) = 4 sizeof (short) = 2 sizeof (long) = 4
Struct1 (char, Int, short, long) offset: 0 4 8 12 sizeof (mystruct1) = 16
Struct2 (char, Int, short, long) offset: 0 2 6 8 sizeof (mystruct2) = 12
Struct3 (char, Int, short, long) offset: 0 1 5 7 sizeof (mystruct3) = 11
Struct3 (char, Int, short, long) offset: 0 4 8 12 sizeof (mystruct3) = 16
# Include <stdio. h>
/* Default byte alignment */
Struct mystruct1 {
Char;
Int B;
Short C;
Long D;
};
/* 2-byte alignment */
# Pragma pack (2)
Struct mystruct2 {
Char;
Int B;
Short C;
Long D;
};
/* 1-byte alignment */
# Pragma pack (1)
Struct mystruct3 {
Char;
Int B;
Short C;
Long D;
};
/* Restore Default byte alignment */
# Pragma pack ()
Struct mystruct4 {
Char;
Int B;
Short C;
Long D;
};
Int main (INT argc, char * argv []) {
Int a_off;
Int B _off;
Int c_off;
Int d_off;
Struct mystruct1 S1;
Struct mystruct2 S2;
Struct mystruct3 S3;
Struct mystruct4 S4;
Printf ("sizeof (char) = % d sizeof (INT) = % d sizeof (short) = % d sizeof (long) = % d/N ",
Sizeof (char), sizeof (INT), sizeof (short), sizeof (long ));
/* Mystruct1 */
A_off = (char *) & (s1.a)-(char *) & S1;
B _off = (char *) & (s1. B)-(char *) & S1;
C_off = (char *) & (s1.c)-(char *) & S1;
D_off = (char *) & (s1.d)-(char *) & S1;
Printf ("struct1 (char, Int, short, long) offset: % d", a_off, B _off, c_off, d_off );
Printf ("sizeof (mystruct1) = % d/N", sizeof (mystruct1 ));
/* Mystruct2 */
A_off = (char *) & (s2.a)-(char *) & S2;
B _off = (char *) & (s2. B)-(char *) & S2;
C_off = (char *) & (s2.c)-(char *) & S2;
D_off = (char *) & (s2.d)-(char *) & S2;
Printf ("struct2 (char, Int, short, long) offset: % d", a_off, B _off, c_off, d_off );
Printf ("sizeof (mystruct2) = % d/N", sizeof (mystruct2 ));
/* Mystruct3 */
A_off = (char *) & (s3.a)-(char *) & S3;
B _off = (char *) & (s3. B)-(char *) & S3;
C_off = (char *) & (s3.c)-(char *) & S3;
D_off = (char *) & (s3.d)-(char *) & S3;
Printf ("struct3 (char, Int, short, long) offset: % d", a_off, B _off, c_off, d_off );
Printf ("sizeof (mystruct3) = % d/N", sizeof (mystruct3 ));
/* Mystruct4 */
A_off = (char *) & (s4.a)-(char *) & S4;
B _off = (char *) & (s4. B)-(char *) & S4;
C_off = (char *) & (s4.c)-(char *) & S4;
D_off = (char *) & (s4.d)-(char *) & S4;
Printf ("struct3 (char, Int, short, long) offset: % d", a_off, B _off, c_off, d_off );
Printf ("sizeof (mystruct3) = % d/N", sizeof (mystruct4 ));
Return 0;
}