C语言 union详解

来源:互联网 发布:网络在线兼职教师招聘 编辑:程序博客网 时间:2024/06/07 03:49

一、定义一个联合类型的一般形式

union 联合名

{

    成员表

};

eg:

union people

{

    int age;

    float weight;

    char *name;

}

在union 中所有的数据成员共用一个空间,同一时间只能储存其中一个数据成员,

1)union 型数据所占的空间等于其最大的成员所占的空间;


union people
{
    char *name;
    int age;
    float weight;
};

int main(int argc, char* argv[])
{
    people p;
    aa = 4.567;
    p.age = 4;
    printf("age = %d\n",p.age);
    p.weight = 4.567f;
    printf("weight = %f\n",p.weight);
    printf("sizeof people is %d\n",sizeof(people));    //输出:sizeof people is4
    printf("sizeof p is %d\n",sizeof(people));    //输出:sizeof p is 4

    return 0;
}

2)所有的数据成员具有相同的起始地址。

大小端模式对union 类型数据的影响

下面再看一个例子:
union
{
   int i;
   char a[2];
}*p, u;
p =&u;
p->a[0] = 0x39;
p->a[1] = 0x38;

p.i 的值应该为多少呢?

这里需要考虑存储模式:大端模式和小端模式。
  1. 大端模式(Big_endian):字数据的高字节存储在低地址中,而字数据的低字节存放在高地址中。(Big Endian:In big endian, you store the most significant byte in the smallest address. )Here's how it would look:
  2. AddressValue1000901001AB1002121003CD

  3. 小端模式(Little_endian):字数据的高字节存储在高地址中,而字数据的低字节则存放在低地址中。(Little Endian:In little endian, you store theleast significant byte in the smallest address. )Here's how it would look:
  4. AddressValue1000CD1001121002AB100390

union 型数据所占的空间等于其最大的成员所占的空间。对union 型的成员的存取都是相对于该联合体基地址的偏移量为0 处开始,也就是联合体的访问不论对哪个变量的存取都是从union 的首地址位置开始。如此一解释,上面的问题是否已经有了答案呢?

请写一个C 函数,若处理器是Big_endian 的,则返回0;若是Little_endian 的,则返回1。

//Answer:

int checkSystem( )
{
   union check
   {
      int i;
      char ch;
   } c;
   c.i = 1;
   return (c.ch ==1);
}

通过该函数确认当前系统的存储模式是大端还是小端。

注意:不过要说明的一点是,某些系统可能同时支持这两种存储模式,你可以用硬件跳线或在编译器的选项中设置其存储模式。

二、联合变量的声明

union w 

   int a; 
   char b; 
}; 
union w  c,d;   //定义两个联合体变量c和d

或者可同时说明为:  
union w 
{  
int a; 
char b;  
}c,d; 


或直接说明为:  
union 
{  
int a; 
char b;  
}c,d;

//其中联合体变量名省略了,直接定义联合体变量c和d

三、使用场合

   1.我们常常使用几个变量,但其中只有一个变量在任意给定的时刻有有效值。

   2.程序处理许多不同类型数据,但是一次只能处理一种,要处理的类型在执行期间确定。

   3.要在不同的时间访问相同的数据,但在不同的情况下该数据的类型是不同的。


0 0
原创粉丝点击