1、共用体
自定义数据类型:结构体和共用体
结构体:
struct A{int a;float b;};//8字节
共用体(联合体):
union B//联合体,共用体{int a;float b;};
特点:
All members share memory,That means all members start from the same low address; in the same union variable,Only one member can be used;
代码示例:
union B//联合体,共用体{int a;float b;};//4字节int main(){union B ua;ua.a = 10;printf("%d\n",ua.a);ua.b = 12.5;printf("%d\n",ua.a);return 0;}
运行结果:
特性利用:Determines whether the current platform is little endian(常考)
小端:Low addresses hold small data,例如short a = 0x0001,If the lower address holds yes0x01则为小端; 代码:
bool IsLittle(){union{char a;short b;}ua;ua.a = 0x0001;return ua.a == 0x01;}int main(){if(IsLittle())//PC是小端{printf("小端\n");}else{printf("大端\n");}return 0;}
运行结果:
2、位段(位域)
struct C//位段{int a:8;//说明a占8位int b:20;int c:4;};//4个字节struct D{int a:10;int b 30;};//8个字节
历史遗留问题,现在不再使用; Because the standard does not stipulate,The storage method of the internal data of the bit segment varies from platform to platform,不可移植; Just need to know the number of bytes it occupies(Must be an integer 倍数);
3、typedef:类型定义
CThe language does not allow function name overloading(Function names must be unique),C++可以
测试代码:
struct Student{char name[20];int age;};int main(){//struct Studnet stu1 = {"caocao",20};//printf("%s,%d\n",stu1.name,stu1.age);Studnet stu2 = {"caocao",20};printf("%s,%d\n",stu2.name,stu2.age);return 0;}
c语言环境–报错:
C++环境–通过:
typedef应用
1)Make a short alias; 2)Aliases based on data characteristics; 例如:size_t
使用:
typedef 类型名 New type name;
例子1:
typedef unsigned long long int uint64; //给unsigned long long int 起一个别名叫 uint64
uint64 —- 64 的意思是 8*8 ,Refers to this type as8个字节
例子2:
typedef int * Pint;//Pint == int * 是定义类型#define PINT int* //是字符替换
重点使用(经常使用):
struct Student{char name[20];int age;};typedef struct Student Studnet;
等价于
typedef struct Student{char name[20];int age;}Studnet;
注意:
老版Clanguage is required,Variables should be defined first,否则会报错: C++Just define it before using it;
例如代码: 运行结果: 错误修改(在前面加 ‘;’):
运行结果(依旧报错): 正确修改(Just change the variable name to the front): 运行结果(问题解决):