转载自:(32条消息) 一文搞懂C语言回调函数_Jensen Lee的博客-CSDN博客_c语言回调函数
博主:Seehidre
转载并加入了个人的理解。
函数指针是指向函数的指针变量。
typedef int (*fun_ptr)(int,int); // 声明一个指向同样参数、返回值的函数指针类型
void (*p)(int,int) = NULL;
函数指针数组
void(*fun_array[5])(int,int,float);
typedef void (*p_func_array)(int, int, float);
p_func_array func_array_2[5];
这两种方法都可以用来定义函数指针数组,它们定义了一个元素个数为5,类型 void (*)(int, int, float) 的函数指针数组。
#include<stdio.h>
int max(int a ,int b){
return a < b? a : b;
}
int main(void){
/*p是函数指针*/
int (* p)(int, int) = & max;
int a,b,c,d;
printf("请输入三个数字:");
scanf("%d %d %d",&a,&b,&c);
d=p(p(a,b),c);
printf("最大的数字是:%d\n",d);
return 0;
}
函数指针变量可以作为某个函数的参数来使用的,回调函数就是一个通过函数指针调用的函数。
回调函数其实是由别人的函数执行时调用你实现的函数。回调函数最大的好处就是解耦,类似Java中工厂模式,通过建立中间工厂来连接两个函数之间的调用,不需要两个函数之间直接调用。
无参数的回调函数
#include<stdio.h>
int callback(){
printf("nihao\n");
}
int handle(int(*p)()){
printf("use callback:\n");
p();
printf("end\n");
}
int main(){
printf("main han shu\n");
handle(callback);//将回调函数当作参数传入,函数指针,函数地址给Handle传入
printf("end\n");
}
有参数回调函数
#include<stdio.h>
int callback(int x){//回调函数
printf("nihao,%d\n",x);
}
int handle(int y,int(*p)(int)){//库函数
printf("use callback:\n");
p(y);
printf("end\n");
}
int main(){//主函数
int a = 1;
printf("main han shu\n");
handle(a,callback);//将回调函数当作参数传入,函数指针,函数地址给Handle传入
printf("end\n");
}