#include <stdio.h>
int sum(int a1 , int b1); int minus(int c1, int d1);
int main() { /*typedef的作用:typedf可以给一个类型定义别名,此后定义变量可以用别名 也可以给定好的别名再次定义别名*/ typedef int MyInt; typedef MyInt MyInt2;//可以放在函数外面做全局变量,位置可以随便写,但是有作用域 MyInt a = 10; MyInt2 b = 20; printf("a=%d, b=%d\n",a, b);
//例2:给指针类型定义一个别名string typedef char * string; string p = "jimmy"; printf("p=%s\n",p);
//例3:给结构体类型定义一个别名 struct student { int age; char * name; double height; }; typedef struct student mystu;//第一种方法 mystu stu1 = {24, "jimmy", 1.78}; printf("%d, %s, %f\n",stu1.age, stu1.name, stu1.height);
typedef struct teacher//方法二 { int age; char * name; double height; } myteacher;/*上面代码等于做了两件事情,一:定了一个结构体变量名;二:定义了结构体变量类型的别名,所以在后面可以用结构体变量的本名,也可以用定义的别名*/ myteacher schoolmast = {38, "jerry", 1.75}; //上面那句代码也可以写成这样 struct teacher school = {38, "jerry", 1.75}; printf("%d, %s, %f\n",schoolmast.age, schoolmast.name, schoolmast.height);
typedef struct //方法三(直接省略变量类型名) { int age; char * name; double height; } leader; leader manager = {38, "sherry", 1.65}; printf("%d, %s, %f\n",manager.age, manager.name, manager.height);
//给指向结构体的指针定义新的类型别名 typedef struct person { int weight; char *name3; } * myper2;/*上面代码等于做了两件事情,一:定了一个结构体变量名;二:给结构体变量类型的指 针定义了一个新的类型别名,在后面可以用结构体变量的本名,也可用定义的别名*/ struct person per = {130, "jimmy"}; struct person * p5 = &per;//常规方法定义指向结构体的指针 printf("weight=%d, name3=%s\n", (*p5).weight, (*p5).name3);
typedef struct person * myper;//用typedef给指向结构体的指针定义别名 myper pp1 = &per; myper2 pp2 =&per; printf("weight=%d, name3=%s\n", pp1->weight, pp1->name3); printf("weight=%d, name3=%s\n", pp2->weight, pp2->name3);
//例4给指向函数的指针定义新的类型别名 //平常写法 int (*p1)(int, int) = sum; int (*p2)(int, int) = minus; //用typedef定义别名 typedef int (*mypoint)(int, int); //mypoint就是类型名称,此后在定义此类指向函数的指针可以这样写: mypoint p3 = sum; mypoint p4 = minus; int result = p3(5, 60); printf("result=%d\n", result);
return 0; }
int sum(int a1 , int b1) { return a1 + b1; }
int minus(int c1, int d1) { return 0; }
|