回调函数的概念
您的理解是正确的。pFunCallBack 是一种函数指针类型,它定义了函数的签名(即函数的参数类型和返回类型)。当我们说 pFunCallBack pFun,我们是在声明一个变量 pFun,其类型是 pFunCallBack —— 即一个函数指针,该指针可以存储指向任何具有相同签名的函数的地址。
在 transFrom 函数中,pFun 作为参数接收这样的一个函数地址。当我们将 show 函数作为参数传递给 transFrom 函数时,我们实际上是在传递 show 函数的地址,这使得 transFrom 能够调用 show 函数来处理数组中的每个元素。
这里的关键点是,show 函数的签名(即它接受一个整型指针作为参数且没有返回值)与 pFunCallBack 类型相匹配,这意味着 show 可以被安全地存储在 pFun 函数指针变量中,并在 transFrom 函数内部被调用。
当 transFrom 在其循环中遇到数组的每个元素时,它通过 pFun 指针调用 show 函数,传递当前元素的地址。show 函数随后使用 printf 打印该元素的值。这种设计允许 transFrom 函数非常灵活,因为它可以被配置为使用不同的回调函数执行不同的操作,而不必修改函数本身。
数组指针指向的是数组的地址,函数指针指向的是函数的地址,函数的名字表示地址的首元素
#define _CRT_SECURE_NO_WARNINGS
#include "math.h"
#include <string.h>
#include "add.h"
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>// 创建函数指针类型
typedef void(*pFunCallBack)(int);// 回调登记函数
void transFrom(int arr[],int len,pFunCallBack pFun)
{for (int i; i < len; i++) {pFun(arr[i]);}
}// 回调函数用来输出数组中的数据
void show(int num)
{printf("%d ", num);
}int main()
{int arr[5] = { 1,2,3,4,5 };transFrom(arr, 5, show);return 0;
}

回调函数不同的函数操作
#define _CRT_SECURE_NO_WARNINGS
#include "math.h"
#include <string.h>
#include "add.h"
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>// 创建函数指针类型
typedef void(*pFunCallBack)(int*);// 回调登记函数
void transFrom(int arr[],int len,pFunCallBack pFun)
{for (int i = 0; i < len; i++) {pFun(&arr[i]);}
}// 回调函数用来输出数组中的数据
void show(int *num)
{printf("%d ", *num);
}void add1(int *num)
{(*num)++;
}// 把数组逆序
void reverse(int* num)
{// 获取到数组的一个if (*num < *(num + 1)) {int t = *num;*num = *(num + 1);*(num + 1) = t;}
}int main()
{int arr[5] = { 1,2,3,4,5 };transFrom(arr, 5, show);transFrom(arr, 5, add1);putchar('\n');transFrom(arr, 5, show);putchar('\n');for (int i = 0; i < 5; i++) {transFrom(arr, 5, reverse);}transFrom(arr, 5, show);return 0;
}
