【C】函数指针
什么是函数指针?
函数指针是C、C++等语言中的一个重要概念,它允许我们将函数的地址存储在一个指针变量中,然后通过这个指针来调用函数。—— 是指针,只不过这个指针存储的是函数的地址
语法是:
返回类型 (*指针变量名)(参数列表);
如:
函数指针pfunc,它的类型是:void (*) (const char, short)
void (*pfunc)(const char*,short)看的时候先看(*pfunc)
常见使用场景
1、回调函数
给函数指针取别名:
typedef int (*fun_t) (int,int)
// 给 int (*) (int,int)类型的变量取个别名,叫fun_t注:如果直接写 int (*fun_t) (int, int):

typedef的作用就是给int (*) (int, int)这个变量类型取了个别名叫fun_t
统一接口:
int calc(int a, int b, fun_t f){return f(a,b);
}主函数里通过这个统一接口使用回调函数:
calc(3, 5, add);
calc(3, 5, sub);注:
int add(int a, int b){return a+b;
}int sub(int a, int b){return a-b;
}引申:函数签名
如:add(int, int) sub(int, int)
函数签名(Function Signature)是函数的唯一标识,组成部分:
函数名
参数列表(参数类型、数量、顺序)
返回类型
完整代码示例:
#include <stdio.h>// 回调函数类型
typedef int (*fun_t)(int, int);// 接受回调函数的函数
int calc(int a, int b, fun_t f) { return f(a, b); }// 具体的回调函数
int add(int a, int b) { return a + b; }int sub(int a, int b) { return a - b; }int main() {printf("%d\n", calc(3, 5, add));printf("%d\n", calc(3, 5, sub));return 0;
}2、函数指针数组
函数指针数组的定义
// 方法1:使用typedef
typedef int (*MathFunc)(int, int);
MathFunc operations[5];// 方法2:直接定义
int (*operations[5])(int, int);完整代码示例
#include <stdio.h>// 定义几个简单的数学运算函数
int add(int a, int b) { return a + b; }int subtract(int a, int b) { return a - b; }int multiply(int a, int b) { return a * b; }int divide(int a, int b) {if (b != 0) return a / b;return 0;
}int modulo(int a, int b) {if (b != 0) return a % b;return 0;
}int main() {// 定义函数指针数组int (*operations[])(int, int) = {add, subtract, multiply, divide, modulo};const char* operation_names[] = {"加法", "减法", "乘法", "除法", "取模"};int a = 10, b = 3;printf("运算示例: a = %d, b = %d\n\n", a, b);// 通过数组索引调用不同的函数for (int i = 0; i < 5; i++) {int result = operations[i](a, b);printf("%s: %d %c %d = %d\n", operation_names[i], a,(i == 0 ? '+' : (i == 1 ? '-' : (i == 2 ? '*' : (i == 3 ? '/' : '%')))),b, result);}return 0;
}运算示例: a = 10, b = 3
加法: 10 + 3 = 13
减法: 10 - 3 = 7
乘法: 10 * 3 = 30
除法: 10 / 3 = 3
取模: 10 % 3 = 1

ai三目运算符这一坨还怪溜的嘞୧(๑•̀◡•́๑)૭
3、函数指针与结构体
结构体类型变量
struct {const char* name, // 运算操作对应的名字int (*operation)(int,int) // 指向运算操作函数的函数指针
}||||||Vtypedef struct {const char* name,int (*operation)(int,int)
} CalculatorOperation;完整代码示例
#include <stdio.h>// 计算器操作
typedef struct {const char* name;int (*operation)(int, int);
} CalculatorOperation;int add(int a, int b) { return a + b; }
int multiply(int a, int b) { return a * b; }int main() {CalculatorOperation operations[] = {{"加法", add},{"乘法", multiply}};int a = 6, b = 7;int count = sizeof(operations) / sizeof(operations[0]);for (int i = 0; i < count; i++) {int result = operations[i].operation(a, b);printf("%s: %d %s %d = %d\n", operations[i].name, a, i == 0 ? "+" : "*", b, result);}return 0;
}加法: 6 + 7 = 13
乘法: 6 * 7 = 42
