1. union 的大小是其中最大数据成员的大小:
#include2. union 的特点是共享内存, 修改一个其他都会变:int main(void){ union MyUnion { short n1; int n2; double n3; }; printf("%u, %u\n", sizeof(union MyUnion), sizeof(double)); getchar(); return 0;}
#include3. 在结构中使用联合:#include int main(void){ union MyUnion { unsigned char n1; unsigned short n2; unsigned int n3; } U = {0}; printf("%10u, %10u, %10u\n", U.n1, U.n2, U.n3); U.n2 = USHRT_MAX; printf("%10u, %10u, %10u\n", U.n1, U.n2, U.n3); U.n3 = INT_MAX; printf("%10u, %10u, %10u\n", U.n1, U.n2, U.n3); U.n1 = 0; printf("%10u, %10u, %10u\n", U.n1, U.n2, U.n3); getchar(); return 0;}
#includeint main(void){ enum UnionTyte{SHORT, INT, FLOAT}; struct Rec { unsigned ID; enum UnionTyte type; /* 识别字段 */ union { /* 联合 */ short s; int i; float f; } u; } R[4]; size_t i; R[0].ID = 1; R[0].type = SHORT; R[0].u.s = 123; R[1].ID = 2; R[1].type = INT; R[1].u.i = 12345; R[2].ID = 3; R[2].type = FLOAT; R[2].u.f = 3.14; R[3].ID = 4; R[3].type = INT; R[3].u.i = 54321; for (i = 0; i < sizeof R / sizeof R[0]; i++) { switch (R[i].type) { case SHORT : printf("%u: %hd\n", R[i].ID, R[i].u.s); break; case INT : printf("%u: %d\n", R[i].ID, R[i].u.i); break; case FLOAT : printf("%u: %g\n", R[i].ID, R[i].u.f); break; } } getchar(); return 0;}