函数指针
函数指针是指向函数的指针,存储函数的入口地址。通过函数指针,可以实现回调函数、函数表、策略模式等高级编程技巧。函数指针的声明语法较复杂,但掌握后能让代码更灵活、更模块化。
声明函数指针
/* 声明:指向返回 int、接受两个 int 参数的函数的指针 */
int (*fp)(int, int);
/* 赋值 */
fp = &add; /* & 可选 */
fp = add; /* 等价 */
/* 调用 */
int result = (*fp)(3, 5); /* 8 */
int result2 = fp(3, 5); /* 等价 */
回调函数
/* 通用处理函数,接受回调 */
void process_array(int arr[], int n, int (*func)(int))
{
for (int i = 0; i < n; i++)
arr[i] = func(arr[i]);
}
/* 回调函数 */
int square(int x) { return x * x; }
int double_val(int x) { return x * 2; }
int arr[5] = {1, 2, 3, 4, 5};
process_array(arr, 5, square); /* arr = {1, 4, 9, 16, 25} */
process_array(arr, 5, double_val); /* arr = {2, 8, 18, 32, 50} */
函数指针数组
/* 计算器 */
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 (*operations[])(int, int) = {add, subtract, multiply};
int result = operations[0](5, 3); /* add(5, 3) = 8 */
result = operations[1](5, 3); /* subtract(5, 3) = 2 */
qsort 的比较函数
#include <stdlib.h>
/* 比较函数 */
int compare_int(const void *a, const void *b)
{
return (*(int *)a - *(int *)b);
}
int arr[] = {3, 1, 4, 1, 5, 9};
qsort(arr, 6, sizeof(int), compare_int);
typedef 简化
/* 定义函数指针类型 */
typedef int (*Operation)(int, int);
Operation op = add;
int result = op(3, 5);
/* 函数指针数组 */
Operation ops[] = {add, subtract, multiply};
常见错误
声明语法错误:
int *fp(int, int); /* 这是函数声明,返回 int* */
int (*fp)(int, int); /* 这是函数指针 */
类型不匹配:
int (*fp)(int, int);
fp = strlen; /* 错误:签名不匹配 */
最佳实践
- 用
typedef简化函数指针类型 - 回调函数用
const void*实现通用接口 - 函数指针数组实现状态机、命令分发
- 确保函数指针类型与指向的函数签名匹配