关键字typedef的作用:给一个数据类型定义别名,在下边的代码中都可以使用这个别名。
应用场景:
1.基本数据类型
2.指向基本数据类型的指针
3.结构体
4.枚举
5.指向函数的指针
6.指向结构体的指针
以下为详细的定义和使用:
- //1.基本数据类型
- typedef int myInt;
- myInt n = 5;
复制代码- //2.指向基本数据类型的指针
- typedef char * string;
- string s1 = "这个以假乱真的string";
复制代码- //3.结构体
- //(1)基本用法
- struct student {
- int age;
- char *name;
- };
- struct student stu1;
- typedef struct student myStudent;
- myStudent stu2;
- //(2)简化用法
- typedef struct student {
- int age;
- char *name;
- } myStudent ;
- myStudent stu3;
- //(3)更简化用法
- typedef struct {
- int age;
- char *name;
- } myStudent ;
- myStudent stu4;
复制代码- //4.枚举
- //(1)基本用法
- enum sex{
- men,
- women
- };
- enum sex sex1;
- typedef enum sex mySex;
- mySex sex2;
- //(2)简化用法
- typedef enum sex{
- men,
- women
- }mySex ;
- mySex sex3;
- //(3)更简化用法
- typedef enum{
- men,
- women
- }mySex ;
- mySex sex4;
复制代码- //5.指向函数的指针
- int func(int a,int b){
- ptintf("%d\n",a+b);
- }
- int (*p)(int,int)=func;
- typedef int (*myPoint)(int,int);
- myPoint p2 = func;
复制代码
- //6.指向结构体的指针
- //(1)基本定义
- struct student {
- int age;
- char *name;
- };
- struct student *p1 = {22,"xiaoming"};
- typedef struct student * myPoint;
- myPoint p2 = {22,"xiaoming"};
- //(2)简单定义
- typedef struct student {
- int age;
- char *name;
- } * myPoint;
- myPoint p3 = {22,"xiaoming"};
- //(3)更简单定义
- typedef struct student {
- int age;
- char *name;
- } * myPoint;
- myPoint p4 = {22,"xiaoming"};
复制代码
|
|