函数指针
函数指针的应用场景+typedef
https://blog.csdn.net/weixin_47921628/article/details/117688224 https://zhuanlan.zhihu.com/p/372557271
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct Student { int id; char name[100]; int score; }Student; //打印输出排序后的结构体 void print(Student a[], int len) { for (int i = 0; i < len; i++) { printf("%d %s %d\t", a[i].id,a[i].name ,a[i].score ); printf("\n"); } } //结构体传参无脑传指针 typedef int(*Stu)(Student* x, Student* y); void bubbleSort(Student a[], int len,Stu stu) { for (int bound = 0; bound < len; bound++) { for (int cur = len - 1; cur > bound; cur--) { // 因为函数指针指向的函数的形参是指针,故实际调用的实参为:&变量名 if (stu(&a[cur - 1], &a[cur]) == 1) { Student temp = a[cur - 1]; a[cur - 1] = a[cur]; a[cur] = temp; } } } } //按照id排列设置回调函数 int idDesc(Student* a, Student* b) { //降序 return a->id < b->id ? 1 : 0; } int idAsce(Student* a, Student* b) { //升序 return a->id > b->id ? 1 : 0; } //按照分数设置回调函数 int scoreDesc(Student* a, Student* b) { return a->score < b->score ? 1 : 0; } int scoreAscec(Student* a, Student* b) { return a->score > b->score ? 1 : 0; } //按照成绩升序排,如果成绩相同按照id 升序排 int scorAsce_idAsce(Student* a, Student* b) { if (a->score == b->score) { return a->id > b->id ? 1 : 0; } return a->score > b->score ? 1 : 0; } int main() { Student arr[] = { {1,"张三",78}, {3,"王五",89}, {4,"赵六",97}, {2,"李四",78} }; int len = sizeof(arr) / sizeof(arr[0]); bubbleSort(arr, len, scorAsce_idAsce); print(arr, len); bubbleSort(arr, len,idAsce); print(arr, len); system("pause"); return 0; }
typedef void(*Func)(void)
为什么能这么用?:相当于定义了一种类型,这个类型具有下面的特征:他是一个函数,没有返回值,没有参数。
所以它还能够
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//构造3个通用函数 void TEST1(void) { printf("test1\n"); }//函数定义 void TEST2(void) { printf("test2\n"); }//函数定义 void TEST3(void) { printf("test3\n"); }//函数定义 ... ... //声明 typdef void (*func)(void); void test(int i) { func vTask[3] = {&TEST1, &TEST2, &TEST3}; func fun = vTask[i]; (*fun)(); }