2011年12月21日 星期三

C/C++中 union 用法

平常因為工作內容的關係, 從沒用過union

今天突然看到, 竟然忘記這資料結構是甚麼 ! 筆記一下大陸人的網頁
#include <stdio.h>
void main()
{
union number
{ /*定义一个联合*/
int i;
struct
{ /*在联合中定义一个结构*/
char first;
char second;
}half;
}num;
num.i=0x4241; /*联合成员赋值*/
printf("%c%c\n", num.half.first, num.half.second);
num.half.first='a'; /*联合中结构成员赋值*/
num.half.second='b';
printf("%x\n", num.i);
getchar();
}
输出结果为: 
AB 
6261 

沒有留言:

張貼留言