#include
#include
using namespace std;
union U1
{
char s[9]; //偏移为0
int n; //偏移为0
double d; //偏移为0
};
union U2
{
char s[5];
int n;
double d;
};
int main(int argc, char *argv[])
{
U1 u1;
U2 u2;
u1.n = 0x010203;
printf("sizeof(U1) = %d\n", sizeof(U1));
printf("sizeof(U1) = %d\n", sizeof(U2));
printf("addr(u1) = 0x%x\n", &u1);
printf("addr(u1.s) %% sizeof(double) = 0x%x %% %d = %d\n", &u1.s, sizeof(double), (unsigned long)(&u1.s) % (sizeof(double)));
printf("addr(u1.n) %% sizeof(int) = 0x%x %% %d = %d\n", &u1.n, sizeof(int), (unsigned long)(&u1.n) % (sizeof(int)));
printf("addr(u1.d) %% sizeof(char) = 0x%x %% %d = %d\n", &u1.d, sizeof(char), (unsigned long)(&u1.d) % (sizeof(char*)));
printf("--------------------------------------\n");
system("pause");
return 0;
}
占用内存为联合体中最大的变量长度的整数倍(特别注意数组)
参考文献:
(1)Union内存对齐及一些例子