#include <stddef.h>
#include <iostream>
struct s1{
int a;
int b;
};
#pragma pack(8)
struct s2{
char c;
int a;
double b;
};
struct s3 {
char b[10];
double a;
};
#pragma unpackstruct s4 {
char c;
int a;
double b;
};
#pragma pack(1)
struct SSS{ /* 13 bytes */
char c; int b;
double a;};
#pragma unpack
struct foo12 {
/* 子結構體要求父結構體適用相同的對齊大小 */
struct foo12_inner {
char *p; /* 8 bytes */
int x; /* 4 bytes */
char pad[4]; /* 4 bytes */
} inner;
char c; /* 1 byte*/
char pad[7]; /* 7 bytes */
};/* 結構體的記憶體對齊,變數的起始地址偏移為 n * min(sizeof(type), pragma pack size) */
union u1 {
char a[14];
int b;
};
union u2 {
char a[17];
double b;
};
/* union 的對齊簡直不懂 ?? union 同時間只能有一個部分被使用, 因此總的空間要能夠提供給每個部分,同時總的空間要與最大的空間對齊 */
int main() {
std::cout << "sizeof s1 " << sizeof(s1) << std::endl
<< "sizeof s2 " << sizeof(s2) << std::endl
<< "sizeof s3 " << sizeof(s3) << std::endl
<< "sizeof s4 " << sizeof(s4) << std::endl
<< "sizeof u1 " << sizeof(u1) << std::endl
<< "sizeof u2 " << sizeof(u2) << std::endl
<< std::endl;
return 0; }
sizeof s1 8
sizeof s2 16
sizeof s3 24
sizeof s4 16
sizeof u1 16
sizeof u2 24