Menu
CoddyTech

函数指针回调

Coddy 面向 Python 开发者的 C 课程的第 38 课,共 48 课。

Python 函数是第一类可调用对象。C 函数指针用于标识签名兼容的函数。当回调需要状态时,请单独传递上下文;普通的 C 函数指针不会像 Python 闭包那样捕获局部变量。

Python

def twice(n):return n*2
print(twice(4))

C17

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
static int twice(int n){return n*2;}
int main(void) {
int (*transform)(int)=twice;printf("%d\n",transform(4));
return 0;
}

移植规则

确保回调签名兼容,并在需要时显式传递状态。

challenge icon

挑战

简单

实现 apply_sum(values,n,transform),将每个元素对应的 transform(value) 相加。输入最多包含 64 个整数。驱动程序会提供一个平方回调函数,还会用另一个回调函数进行测试,以确保确实调用了该回调函数。输入为空时返回 0。

编辑未锁定的源文件和头文件。确保声明的公共 API 与可见的已锁定 main.c 兼容,因为它会直接调用该函数。不要添加另一个 main。除非任务明确检查数值范围,否则所有数值任务测试数据都足够小,不会溢出。只打印指定的输出;如果展示了驱动程序,它会负责解析输入和输出。

亲手试试

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
#include "lesson.h"
static int square(int n){return n*n;}
static int offset(int n){return n+7;}
int main(void){int probe[]={1,2};if(apply_sum(probe,2,offset)!=17)return 3;int values[64];size_t n=0;int value;while(n<64 && scanf("%d",&value)==1)values[n++]=value;printf("%d\n",apply_sum(values,n,square));return 0;}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 Python 开发者的 C中的所有课

自己练习: C 在线编译器