typdef union { int n; char c; } NC; nc.c 确实有 *(char *)&nc 的意思 nc.n 确实有 *(int *)&nc 的意思 (存取方式) 我觉得,可以用union去描述同一概念,但不会同时出现的东西。 比如 union mark { int score; char grade; } 写程序时,别人比较容易理解;改的时候也容易。 The primary usefulness of a union is to conserve space, since it provides a way of letting many different types be stored in the same space. Unions also provide crude polymorphism. However, there is no checking of types, so it is up to the programmer to be sure that the proper fields are accessed in different contexts. The relevant field of a union variable is typically determined by the state of other variables, possibly in an enclosing struct. (union常不是单独使用,而是与struct一起,它的值常是由密封在struct中的其他变量的状态决定的) 举个例子: [php] struct in6_addr { union { uint8_t u6_addr8[16]; uint16_t u6_addr16[8]; uint32_t u6_addr32[4]; } in6_u; #define s6_addr in6_u.u6_addr8 #define s6_addr16 in6_u.u6_addr16 #define s6_addr32 in6_u.u6_addr32 }; [/php] uinion在协议里用的很多 |
|