共用体
共用体是构造数据类型的一种
共用体也常被称为联合体
共用体的实质
共用体是单个存储单位上的元素集合
注意:元素都在一个存储单位上,这个存储单位的大小是最大数据类型的大小
共用体的作用
我们用共用体并不是内存空间不够用
用共用体时,主要利用”元素都存储到一个存储单位上”这一特性
共用体的组成
共用体是依靠不同的数据类型的组合创建起来的,数组的元素可以是之下的任何几种的组合
- 整型
- 浮点型
- 字符型
- 指针型
- 枚举型
- 数组
- 结构体
- 共用体
共用体的声明
union hello{
int hello;
char c[100];
struct hello * p;
};
共用体变量的定义
union hello hello;
共用体使用示例
#include <stdio.h>
union hiahia{
int i;
char c;
} b;
int main(int argc, const char *argv[])
{
b.i = 1;
if(b.c){
printf("this machine follows the little endian \n");
}else{
printf("this machine follows the big endian \n");
}
return 0;
}
static int IsBigEndian(void){
union hiahia{
int i;
char c;
} b;
b.i = 1;
return !b.c;
}
static int IsBigEndian(void){
int i = 1;
return !*(char*)&i;
}