(union, struct) 相互巢狀使用----技巧(你肯定沒見過)
阿新 • • 發佈:2019-01-02
#include <stdlib.h> #include <stdio.h> // 參考 Glibc庫原始碼 sig_info.h typedef struct info{ int age; union { int code; struct { int pid; int uid; } id; struct { int KM; char *addr_name; } address; } u; } info_t; #define code u.code #define pid u.id.pid #define uid u.id.uid #define KM u.address.KM #define addr_name u.address.addr_name int main(int argc, char **argv) { info_t info; info.age = 20; info.code = 5; printf("age = %d\n", info.age); // 20 printf("code = %d\n", info.code); // 5 printf("----------------------\n"); info.pid = 123; printf("age = %d\n", info.age); // 20 printf("code = %d\n", info.code); // 123, 因為code變數與id變數共用一塊記憶體 printf("pid = %d\n", info.pid); // 123 printf("----------------------\n"); info.KM = 789; printf("age = %d\n", info.age); // 20 printf("code = %d\n", info.code); // 789, 因為code變數與address變數共用一塊記憶體 printf("pid = %d\n", info.pid); // 789, 因為id變數與address變數共用一塊記憶體 printf("KM = %d\n", info.KM); // 789 return 0; }
執行結果:
[email protected]_hua_shu:~/test$ gcc union_struct.c
[email protected]_hua_shu:~/test$ ./a.out
age = 20
code = 5
----------------------
age = 20
code = 123
pid = 123
----------------------
age = 20
code = 789
pid = 789
KM = 789
[email protected]_hua_shu:~/test$