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 的值应该为多少呢?
这里需要考虑存储模式:大端模式和小端模式。
- 大端模式(Big_endian):字数据的高字节存储在低地址中,而字数据的低字节存放在高地址中。(Big Endian:In big endian, you store the most significant byte in the smallest address. )Here's how it would look:
AddressValue1000901001AB1002121003CD - 小端模式(Little_endian):字数据的高字节存储在高地址中,而字数据的低字节则存放在低地址中。(Little Endian:In little endian, you store theleast significant byte in the smallest address. )Here's how it would look:
AddressValue1000CD1001121002AB100390
请写一个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.要在不同的时间访问相同的数据,但在不同的情况下该数据的类型是不同的。
- C语言 union详解
- c语言 union
- C语言联合体union
- C语言 union
- C语言union关键字
- C语言联合体union
- C 语言Union用法
- c语言 union 联合体
- C语言联合体 union
- C语言union关键字
- C语言Union学习
- C语言union关键字
- C语言union关键字
- C语言union关键字
- C语言union关键字
- C语言union关键字
- C语言union关键字
- C语言中的UNION
- 输入三个数,按小到大排列输出
- Algorithm学习笔记 --- 求一个数的平方(函数重载)
- Cocos2dx之通过JNI实现c/c++和Android的java层函数互调
- asdasdasdasd
- 1001. 害死人不偿命的(3n+1)猜想 (15)
- C语言 union详解
- 对JAVA Bean使用PropertyDescriptor反射调用JAVA方法
- 择一城终老,遇一人白首
- ABCDE5人竞赛真话假话
- linux中用户与用户组的一般管理
- String.getBytes()
- Occlusion Reasoning for Object Detection under Arbitrary Viewpoint总结
- setting
- 1002. 写出这个数 (20)