函数指针又称指向函数的指针指的是一个指针变量其值为一个函数的地址。对于函数指针的使用包含以下部分。对于函数指针具体示例如下所示。#include // 定义指向函数的指针的类型 typedef int (*func_ptr)(int, int); typedef struct { int a; int b; // 声明函数指针 func_ptr add_func; }STRUCT_DEMO; static int add(int a, int b) { return a b; } int main(int argc, char *argv[]) { STRUCT_DEMO demo; demo.a 1; demo.b 2; // 赋值函数指针变量 demo.add_func add; // 调用函数指针输出结果 printf(%d\n, demo.add_func(demo.a, demo.b)); // 输出3 return 0; }对于函数指针常用方式就是结合数组指针实现通过列表访问对应的函数在协议解析和事件处理时可以使用分支处理具体如下所示。#include typedef int (*func_ptr)(int, int); static int math_add(int a, int b) { return a b; } static int math_sub(int a, int b) { return a - b; } static int math_mul(int a, int b) { return a * b; } static int math_div(int a, int b) { return a / b; } #define MATH_ADD 0 #define MATH_SUB 1 #define MATH_MUL 2 #define MATH_DIV 3 func_ptr math_func[4] { math_add, math_sub, math_mul, math_div }; int main(int argc, char *argv[]) { int a 1; int b 2; int id 0; // 调用函数指针输出结果 id MATH_ADD; printf(MATH_ADD: %d\n, math_func[id](a, b)); // 输出3 id MATH_SUB; printf(MATH_SUB: %d\n, math_func[id](a, b)); // 输出-1 id MATH_MUL; printf(MATH_MUL: %d\n, math_func[id](a, b)); // 输出2 id MATH_DIV; printf(MATH_DIV: %d\n, math_func[id](a, b)); // 输出0 return 0; }对于上述代码指向结果如下所示。可以看到如果id表示在协议解析和事件处理中的编号就可以直接通过数组加指针函数的方式进行调用同时代码中也可以对支持的事件和执行函数进行统一管理是常用的开发方案。