focus on linux, c/c++, lua

union

以前对union的理解不是很深刻,也很少用到这个数据结构,今天在看CloudWu的gc代码时,他貌似很喜欢用union和struct的层层嵌套,我又顺便google了一下union,写点东西加深一下自己的理解,首先看一段代码如下。

int main()
{
   union
{
   int i;
   struct st
   {
    char a;
    char b;
   }half;
}all;

all.i = 0x1122; // union的这块内存值即为0001 0001 0010 0010 a即为低8位,b为高8位
printf("%x%x\n", all.half.a , all.half.b);
all.half.a = 0x22; // 同样道理a占低8位
all.half.b = 0x11; // b占高8位
printf("%d\n", all.i);
system("pause");
return 0;
}

输出:

2211

4386


posted on 2010-10-20 10:41 zuhd 阅读(289) 评论(0)  编辑 收藏 引用 所属分类: c/c++


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理