C 语言 函数指针和函数指针数组

1. 函数也有地址

C 语言里,函数和变量一样,都有自己的地址。

既然有地址,就能被指针指向。


2. 函数指针的声明方式

格式:

复制代码
返回值类型 (*指针名)(参数列表)

例:

复制代码
int (*fp)(int, int);

表示:

  • fp 是一个指针

  • 它指向一个参数为 (int, int) 的函数

  • 返回值 int


3. 函数指针的初始化

复制代码
fp = add;

C 中函数名本质上就是函数地址。


4. 使用函数指针调用函数

复制代码
int r = fp(1,2);

它和直接 add(1,2) 完全等价。


5. typedef 简化写法

复制代码
typedef int (*callback)(int); callback cb = func;

优点:

  • 可读性强

  • 使用方便


6. 函数指针数组

你可以把多个函数指针装入数组:

复制代码
callback table[3] = {func1, func2, func3};

然后通过索引调用:

复制代码
table[1]();

示例:

复制代码
#include <stdio.h>

typedef enum {
  A_TO_B,
  B_TO_A,
  A_TO_C,
  C_TO_A,
  C_TO_B,
  B_TO_C,
  STATUS_MAX,
} Status;

struct Car {
  Status current_status;
};

typedef int (*callback)(struct Car*);

int a2b(struct Car*car) {
  // a到b所需要做的行为
  printf("a到b\n");
  return 1;
}

int b2a(struct Car *car) {
  // b到a所需要做的行为
  printf("b到a\n");
  return 1;
}

int a2c(struct Car *car) {
  // a到c所需做的行为
  printf("a到c\n");
  return 1;
}

int c2a(struct Car *car) {
  // c到a所需要做的行为
  printf("c到a\n");
  return 1;
}

int c2b(struct Car *car) {
  // c到b所需要做的行为
  printf("c到b\n");
  return 1;
}

int b2c(struct Car *car) {
  // b到c所需要做的行为
  printf("b到c\n");
  return 1;
}

int main() {
  callback callbacks[STATUS_MAX] = {a2b, b2a, a2c, c2a, a2b, b2c};
  Status status[4] = {A_TO_B, B_TO_A, A_TO_C, C_TO_A};
  int i = 0;
  struct Car car;
  car.current_status = status[i];

  while (i < 4) {
    // 状态结束
    if (callbacks[car.current_status](&car)) {
      i++;
      car.current_status = i;
      //i %= 4; // 处理状态的个数
    }
  }
}
相关推荐
JieE2129 小时前
LeetCode 56. 合并区间|超清晰 JS 图解思路,面试高频区间题
javascript·算法·面试
Jack2017 小时前
HarmonyOS开发中错误处理策略:网络异常统一处理
算法
小小杨树18 小时前
读懂色彩:拍照调色不再难
算法·计算机视觉·配色
JieE2121 天前
LeetCode 226. 翻转二叉树|JS 递归超详细拆解,二叉树入门经典题
javascript·算法
JieE2121 天前
LeetCode 104. 二叉树的最大深度|递归思路超详细拆解
javascript·算法
vivo互联网技术2 天前
CVPR 2026 | 全新强化学习框架 BeautyGRPO:重塑真实人像
算法·大模型·cvpr·影像
Darling噜啦啦2 天前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
用户497863050732 天前
(一)小红的数组操作
算法·编程语言
怕浪猫2 天前
Electron 系列文章封面图
算法·架构·前端框架