Gcc defines two statements for modifying the data structure alignment.
1. # pragma pack ()
2. _ attribute _ (packed ))
# Include <stdio. h>
# Include <stdlib. h>
# Include <string. h>
// Calculate the offset of t in S
# Define offsetof (S, t) (size_t) & (S *) 0)-> t)
Typedef struct _ S1 {
Char;
Char B;
Double c;
} S1;
// _ Attribute _ (packed) means no alignment optimization
Typedef struct _ S2 {
Char;
Char B;
Double c;
}__ Attribute _ (packed) S2;
Typedef struct _ Y
{
Int;
Int B;
Char C;
Char content [0];
} Y;
# Pragma pack (push, 4)
Struct A_4
{
Short V1;
Int V2;
};
# Pragma pack (POP)
# Pragma pack (push, 1)
Struct A_1
{
Short V1;
Int V2;
};
# Pragma pack (POP)
Int main ()
{
//The effect of _ attribute _ (packed), after _ attribute _ (packed) is used, no padding is available.
Printf ("/nsizeof (S1) = % u, offsetof (S1, c) = % u/N", sizeof (S1), offsetof (S1, c ));
Printf ("sizeof (S2) = % u, offsetof (S2, c) = % u/N", sizeof (S2), offsetof (S2, c ));
//This structure is very interesting. This structure Y is not optimized, so the compiler adds some padding to the end of this structure.
.
//So the size of this struct is 12, but the content offset is 9.
Printf ("sizeof (Y) = % u, offsetof (Y, content) = % u, offsetof (Y, c) = % u/n", sizeof (Y ), offsetof (Y, content), offsetof (Y, c ));
//One example of # pragma pack () directives
Printf ("sizeof (a_1) = % u/n", sizeof (struct a_1 ));
Printf ("sizeof (a_4) = % u/n", sizeof (struct a_4 ));
Getchar ();
Return 0;
}