时间会过去,只有记忆不会 函数指针和回调函数 |
指针函数:
在程序编译的时候会为函数分配一个入口地址,这个地址也就称为函数的指针,函数名代表函数的入口地址。
typedef int(p)(int,int);
void my_func(int a,int b){
printf("%d %d",a,b);
}
void test()
{
p* p=my_func();
p2(10,20);
}
指针函数:指向函数的指针
- 函数指针定义方式(先定义函数类型,根据类型定义指针变量);
- 先定义函数指针类型,根据类型定义指针变量;
- 直接定义函数指针变量;
int my_func(int a,int b)
{
printf("ret:%d\n",a+b);
return 0;
}
//1.先定义函数类型,通过类型定义指针
void test01()
{
typedef int(FUNC_TYPE)(int,int);
FUNC_TYPE* f = my_func;
//如何调用?
(*f)(10,20);
f(10,20);
}
//定义函数指针类型
void test02()
{
typedef int(*FUNC_POINTER)(int,int);
FUNC_POINTER f = my_func;
//如何调用?
(*f)(10,20);
f(10,20);
}
//直接定义函数指针变量
void test03()
{
int(*f)(int,int) = my_func;
//如何调用?
(*f)(10,20);
f(10,20);
}
函数指针数组:每个元素都是函数指针
void func01(int a)
{
printf("func01:%d\n",a);
}
void func02(int a)
{
printf("func01:%d\n",a);
}
void func03(int a)
{
printf("func01:%d\n",a);
}
void test()
{
#if 0
//定义函数指针
void(*func_array[])(int) = {
func01, func02,func03};
#else
void (*func_array[3])(int);
func_array[0] = func01;
func_array[1] = func02;
func_array[2] = func03
#endif
for(int i=0;i<3;i++)
{
func_array[i](10+i);
(*func_array[i](10+i));
}
}
回调函数:就是相当于函数指针做函数参数
void fun(int (*p)(int a))
int plus(int a, int b)
{
return a + b;
}
int sub(int a, int b)
{
return a - b;
}
int mul(int a, int b)
{
return a * b;
}
int division(int a, int b)
{
return a / b;
}
void Calculator(int (*myCalculate)(int,int),int a,int b)
{
int ret = myCalculate(a,b);
printf("ret = %d\n",ret);
}
void test()
{
int num1=10;
int num2=20;
Calculator(plus, num1, num2);
}
函数指针是指向函数的指针;
指针函数是返回类型为指针的函数;