//以下默认的结构成员对齐为8字节
The following sample shows how to the pack pragma to change the alignment of a structure.
// pragma_directives_pack.cpp
#include <stddef.h>
#include <stdio.h>
struct S {
int i; // size 4
short j; // size 2
double k; // size 8
};
#pragma pack(2)
struct T {
int i;
short j;
double k;
};
int main() {
printf("%d ", offsetof(S, i));
printf("%d ", offsetof(S, j));
printf("%d/n", offsetof(S, k));
T tt;
printf("%d ", offsetof(T, i));
printf("%d ", offsetof(T, j));
printf("%d/n", offsetof(T, k));
}
#include <stddef.h>
#include <stdio.h>
struct S {
int i; // size 4
short j; // size 2
double k; // size 8
};
#pragma pack(2)
struct T {
int i;
short j;
double k;
};
int main() {
printf("%d ", offsetof(S, i));
printf("%d ", offsetof(S, j));
printf("%d/n", offsetof(S, k));
T tt;
printf("%d ", offsetof(T, i));
printf("%d ", offsetof(T, j));
printf("%d/n", offsetof(T, k));
}
-----------------
Result:
0 4 8 0 4 6
浙公网安备 33010602011771号