1·共用体类型的定义、变量定义、和使用
1·1 共用体union与结构体struct在类型定义,变量定义,使用方法上很相似。
1·2 共用体 与 结构体的使用区别
#include <stdio.h>
// a 和 b其实指向同一块内存空间,只是对这一块空间的不同解析方式。
// 如果使用u1.a 就是用int类型解析这个共用体,如果是u1.b就是用char类型解析。
union myunion
{
int a;
char b;
};
struct mystruct
{
int a;
char b;
};
int main (void)
{
union myunion u1;
u1.a = 12;
printf("u1.b = %d\n",u1.b ); // u1.b = 12
struct mystruct s1;
s1.a = 12;
printf("s1.b = %d\n",s1.b ); // s1.b = 0
return 0;
}
1·3 union 所占字节大小 由各个元素里面占用内存最大的那个元素的大小决定(一致)。union中的元素不存在内存对齐的问题,因为union中实际只有一个元素,都是从一个地址开始的(开始地址就是整个union占有内存空间恶首地址),谁愿意不涉及内存对齐。
1·4 struct是对各独立元素打包在一起,union是一个元素的多种不同解析方式。
1·5 union的主要用途
共用体用在 对同一个内存空间的不同解析。
2· 大小端模式
高位 对应 高地址 —小端
高位 对应 低地址 —大端
注意:大小端本身没有优劣,所以要求存储时和读取时按照同样大小端模式来进行,否者出错。
2·1 代码检测当前系统的大小端
方法1:用union来检测
#include <stdio.h>
union endian
{
int a;
char b;
};
int main (void)
{
union endian u1;
u1.a = 1;
if(u1.b = 1)
printf("little\n");
else if (u1.b = 0)
printf("big\n");
else
printf("test error\n");
return 0;
}
方法2:用指针
#include <stdio.h>
int test_endian(void)
{
int a = 1;
char b = *((char *)(&a)); // 这里是对a的地址解引用取出a存储的数据,在赋值给b
return b;
}
int main(int argc, char const *argv[])
{
int i = test_endian();
if (i == 1)
{
printf("little\n");
/* code */
}
else
printf("big\n");
return 0;
}
3·枚举
3·1 枚举是什么?
枚举在C语言中其实就是一些符号常量集。将int类型数字 与 自定义的名字绑定。
#include <stdio.h>
// 这个枚举表示函数的返回值是对还是错
enum return_value // 枚举类型!这里可以好好理解
{
ERROR,
RIGHT,
};
enum return_value test(void)
{
enum return_value r1;
r1 = ERROR;
return r1 ;
}
int main(void)
{
enum return_value r = test();
if (r == RIGHT)
{
printf("function return RIGHT\n");
/* code */
}
else
printf("function return ERROR\n");
return 0;
}