在結構中, 每個欄位的資料類型是唯一的; 使用聯合可以在一個欄位中儲存不同的資料類型.
不同的資料類型共用一塊記憶體. 當然其記憶體大小應依著大的來.
聯合中的資料, 非此即彼, 只有一個有效; 應該有說明在某個資料中此時有用的是什麼類型.
除了共用記憶體以外, 聯合與結構一樣.
1. union 的大小是其中最大資料成員的大小:
#include <stdio.h>int main(void){ union MyUnion { short n1; int n2; double n3; }; printf("%u, %u\n", sizeof(union MyUnion), sizeof(double)); getchar(); return 0;}
2. union 的特點是共用記憶體, 修改一個其他都會變:
#include <stdio.h>#include <limits.h>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;}
3. 在結構中使用聯合:
#include <stdio.h>int 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