半路出家的我,初次看到 typedef int (* deal_date)(struct arr date);这类代码时,较为困惑,查了一些资料才明白,这代码的用法,下面做个总结。
函数指针的使用
函数指针是指向函数所在空间的指针。一个函数总是占用一段连续的内存区域,函数名在表达式中有时也会被转换为该函数所在内存区域的首地址,这和数组名非常类似。我们可以把函数的这个首地址(或称入口地址)赋予一个指针变量,使指针变量指向函数所在的内存区域,然后通过指针变量就可以找到并调用该函数。这种指针就是函数指针。
#include <stdio.h>
struct arr
{
int a;
int b;
};
//返回两个数中较大的一个
int max(struct arr num){
int a, b;
a = num.a;
b = num.b;
return a>b ? a : b;
}
//返回两个数中的和
int add(struct arr num){
int a, b;
a = num.a;
b = num.b;
return a+b;
}
// 方法1:定义了一个函数指针pfun,这个函数指针的返回值为int型,
int (* pfun)(struct arr date);
// 方法2:定义函数指针类型,该指针类型指向的函数,
// 输入为struct arr 类型,输出为int 类型
typedef int (* deal_date)(struct arr date);
// 用定义好的函数指针类型 定义了一个指针变量,
deal_date deal_result;
int main(){
int x, y, result;
struct arr in;
printf("Input two numbers:");
scanf("%d %d", &x, &y);
in.a = x;
in.b = y;
// 根据条件不同,对函数指针变量赋不同的 函数地址
if(x>y){
deal_result = max;
// 然后我们给函数指针赋值,赋值为max,也就是max函数的首地址;
pfun = max;
} else {
deal_result = add;
pfun = add;
}
result = deal_result(in);
// 最终调用pfun();也就相当于调用了max()或add();
result = pfun(in);
printf("result: %d\n", result);
return 0;
}
typedef int (* deal_date)(struct arr date);
1.* deal_date:deal_date是一个指针类型,类似于int
2.(* deal_date)():表明该指针类型指向一个函数
3.(* deal_date)(struct arr date):这个函数有一个参数,类型为struct arr
4.int (* deal_date)(struct arr date):这个函数有一个返回值,类型为int
5.typedef int (* deal_date)(struct arr date):前面有个typedef,所以现在 deal_date 是这种类型的别名
deal_date deal_result;
用定义好的函数指针类型 定义了一个指针变量,该指针变量可以指向任何符合该输入输出类型的函数
注意:
int (* deal_date)(struct arr date);中( )
的优先级高于*
,第一个括号不能省略,如果写作int * deal_date(struct arr date);;
就成了函数原型的定义,它表明函数的返回值类型为int *
函数指针的好处
可参考以下文章:
https://blog.csdn.net/wujiangguizhen/article/details/17153495
https://blog.csdn.net/windyblankboy/article/details/52264475
回调函数
回调函数:通过函数指针调用的函数。如果把函数的指针(地址)作为参数传递给另一个函数,当这个指针被用来调用其所指向的函数时,我们就说这是回调函数。回调函数不是由该函数的实现方直接调用,而是在特定的事件或条件发生时由另外的一方调用的,用于对该事件或条件进行响应。
可参考以下文章详细了解:
https://blog.csdn.net/weixin_39939425/article/details/90298435