一、函数 实现某特定功能的代码
1)函数名与数组名一样是地址
2)函数指针 指向函数的指针 可以通过函数指针调用指向的函数
3)返回值类型 (*函数指针名)(参数类型) = 函数名
int maxValue(int a,int b){ return a > b ? a : b; } int (*p)(int,int) = maxvalwe; printf("%d\n",p(3,4)); //用指针去调用函数
4) 示例代码
int maxValue(int a,int b){ return a > b ? a : b; } int sumValue(int a,int b){ int sum = a+b; return sum; } int main(int argc, const char * argv[]) { int (*p)(int,int) = NULL; int n = 0; scanf("%d",&n); switch (n) { case 1: p = maxValue; break; case 2: p = sumValue; break; default: printf("不在服务区"); break; } if (p!=NULL) { printf("%d",p(3,5)); } return 0; }
5)按学生成绩进行升序排列 成绩90以上者 名字后面加高富帅
typedef struct student{ char name[20]; char gender; int age; float score; }Student; void print(char *name){ strcat(name, "高富帅"); } void findvalue(Student *s,int count,void(*p)(char *)){ for (int i =0; i<count; i++) { if (s[i].score > 90) { p(s[i].name); } printf("%s %c %d %f\n",s[i].name,s[i].gender,s[i].age,s[i].score); } } int main(int argc, const char * argv[]) { Student stu[3] = {{"xiao",‘m‘,23,70},{"ming",‘f‘,24,91},{"zhang",‘m‘,28,95}}; Student *s = stu; findvalue(s,3,print); return 0; }
6)实现函数动态排列
typedef struct student{ char name[20]; char gender; int age; float score; }Student; typedef BOOL(*sortAll)(Student stu1,Student stu2);//定义一个函数指针类型 void sortStudent(Student *s,int count,sortAll al)//函数指针指向函数(sortAge) { for (int i = 0; i < count-1; i++) { for (int j = 0; j < count-1-i; j++) { //函数回调 if (al(s[j],s[j+1])) { Student temp = s[j]; s[j] = s[j+1]; s[j+1] = temp; } /*通过函数指针al指向函数(sortAge) *所以s[j],s[j+1]这两个参数也指向函数(sortAge)的形参变量stu1,stu2 if(al(s[j]),s[j+1]) 等价于 if(s[j].age > s[j+1].age) */ } } for (int i =0; i<count; i++) { printf("%s %c %d %.2f\n",s[i].name,s[i].gender,s[i].age,s[i].score); } } BOOL sortAge(Student stu1,Student stu2) { return stu1.age > stu2.age; } int main(int argc, const char * argv[]) { Student stu[3] = {{"xiao",‘m‘,23,70},{"ming",‘f‘,24,91},{"zhang",‘m‘,28,95}}; Student *s = stu; sortStudent(s,3,sortAge); return 0; }
原文:http://www.cnblogs.com/ChinaTiger/p/4722244.html