Skip to content

C 函数指针与回调函数

函数指针用于保存函数的地址,可实现回调、策略模式、事件处理等。本章详细讲解声明方式、调用方法与实战示例。

1. 函数指针声明

c
int add(int, int);
int (*fp)(int, int) = add; // 声明并初始化

2. 通过函数指针调用

c
printf("%d\n", fp(2,3)); // 与 add(2,3) 等效

3. 作为参数(回调)

c
typedef int (*binop)(int,int);

int calc(int a, int b, binop op) { return op(a,b); }

4. 数组与表驱动

c
int add(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;}

binop ops[] = { add, sub, mul };

5. 与结构体组合

c
typedef struct { const char* name; binop op; } Entry;
Entry table[] = { {"add",add}, {"sub",sub}, {"mul",mul} };

6. 回调示例:排序比较函数

c
#include <stdlib.h>
int cmp_int(const void* a, const void* b) {
    int x = *(const int*)a, y = *(const int*)b;
    return (x>y) - (x<y);
}
// qsort(arr, n, sizeof(int), cmp_int);

7. 指向返回指针/函数的函数指针(进阶)

c
int* ret_ptr(void);
int (*ret_func(void))(int,int); // 返回函数指针的函数

8. 小结

熟练掌握函数指针有助于构建可扩展、低耦合的 C 程序结构,常用于库回调、事件分发与策略切换。

本站内容仅供学习和研究使用。