int max(int a, int b) { return a > b ? a : b; }
int (*fp)(int, int) = max; // fp 指向 max
int r = fp(3, 5); // 呼叫 → 5
宣告技巧:返回類型 (*指標名)(參數列表),參數名可省略。
void process(int a, int b, int (*op)(int, int)) {
printf("Result: %d\n", op(a, b));
}
process(3, 5, max); // 8
process(3, 5, add); // 8 (假設 add 存在)
int cmp_int(const void *p1, const void *p2) {
return *(const int*)p1 - *(const int*)p2;
}
qsort(arr, n, sizeof(int), cmp_int);
typedef struct { char name[20]; int age; float score; } Student;
int cmp_score(const void *p1, const void *p2) {
const Student *s1 = p1, *s2 = p2;
return (s1->score > s2->score) - (s1->score < s2->score);
}
int cmp_age(const void *p1, const void *p2) {
return ((Student*)p1)->age - ((Student*)p2)->age;
}
// 使用
qsort(students, n, sizeof(Student), cmp_score); // 按分數
qsort(students, n, sizeof(Student), cmp_age); // 按年齡
typedef void (*CmdFunc)(void);
void cmd_help(void) { puts("Help"); }
void cmd_quit(void) { exit(0); }
CmdFunc cmds[] = { cmd_help, cmd_quit };
// 解析輸入索引 idx
if (idx >= 0 && idx < 2) cmds[idx]();
typedef struct {
int x, y;
void (*draw)(struct Shape*);
void (*move)(struct Shape*, int, int);
} Shape;
void draw_rect(Shape *s) { printf("Rect at (%d,%d)\n", s->x, s->y); }
void move_rect(Shape *s, int dx, int dy) { s->x += dx; s->y += dy; }
Shape rect = { 10, 20, draw_rect, move_rect };
rect.draw(&rect);
rect.move(&rect, 5, 5);
| 錯誤 | 修正 |
|---|---|
int *fp(int, int) 宣告函數返回指標 | int (*fp)(int, int) |
調用時寫 fp(3,4) 但 fp 未初始化 | 必須先賦值 fp = func; |
| 回調函數簽名不匹配 | 嚴格對應參數/返回型別 |
成員函數指標缺少 struct Shape* 參數 | 手動傳遞 this 指標 |