首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

iOS 學習筆記 Day 11:C 函數指標完全掌握——定義、回呼、動態排序與映射表驅動

     編輯:關於C語言

函數指標基本語法

// 函數原型: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 分派等場景
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved