函數指標基本語法
// 函數原型:int sum(int, int)
int (*p)(int, int) = sum; // p 指向 sum
printf("%d", p(5, 8)); // 透過指標呼叫
// typedef 簡化
typedef int (*FP)(int, int);
FP fp = sum;
回呼模式:將演算法作為參數傳遞
int getValue(int x, int y, int (*op)(int, int)) {
return op(x, y);
}
int sum(int a, int b) { return a+b; }
int max(int a, int b) { return a>b?a:b; }
getValue(10, 8, sum); // 18
getValue(10, 8, max); // 10
動態排序:策略模式的 C 實現
typedef struct { char name[20]; float score; int age; float attend; } Student;
typedef BOOL (*CmpFP)(Student, Student);
BOOL byAge(Student a, Student b) { return a.age > b.age; }
BOOL byScore(Student a, Student b) { return a.score > b.score; }
void sortArray(Student *arr, int n, CmpFP cmp) {
for (int i=0;i
函數指標作為返回值:字串映射函數表
typedef int (*PFUN)(int, int);
struct Map { char name[30]; PFUN fun; } map[] = {
{"max", max}, {"min", min}, {"sum", sum}, {"mul", mul}, ...
};
PFUN findFun(char *name) {
for (auto &m : map) if (strcmp(m.name, name)==0) return m.fun;
return max; // default
}
int getValue(int x, int y, char *name) { return findFun(name)(x, y); }
// 呼叫
getValue(8, 12, "mul"); // 96
核心觀念
- 函數指標**本質是位址**,指向程式碼區
- 回呼實現「控制反轉」,演算法與資料結構解耦
- 映射表驅動可將字串指令動態綁定函數,適用於指令解析器、RPC 分派等場景