19. C语言回调函数

回调函数

  回调函数就是⼀个通过函数指针调⽤的函数。如果你把函数的指针(地址)作为参数传递给另⼀个函数,当这个指针被⽤来调⽤其所指向的函数时,我们就说这是回调函数。回调函数不是由该函数的实现⽅直接调⽤,⽽是在特定的事件或条件发⽣时由另外的⼀⽅调⽤的,⽤于对该事件或条件进⾏响应。

  我们看两个回调的例子。

例1:使用回调函数实现计算器

    #include <stdio.h>
    #include <stdlib.h>

    int add(int a,int b) {
        return a+b;
    }
    int sub(int a,int b) {
        return a-b;
    }
    int mul(int a,int b) {
        return  a*b;
    }
    int div(int a,int b) {
        return a/b;
    }

    // 计算器
    void calc(int (*pfunc)(int,int))
    {
        int x = 0;
        int y = 0;
        scanf("%d%d",&x,&y);
        printf("result = %d\n",pfunc(x,y));
    }   

    int main()
    {
        int input = 0;
        printf("请输入参数:>");
        scanf("%d", &input);
        switch(input)
        {
            case 1:
                calc(add);
                break;
            case 2:
                calc(sub);
                break;
            case 3:
                calc(mul);
                break;
            case 4:
                calc(div);
                break;
            default:
                break;
        }
    } 

例2:使用回调函数模拟实现 qsort (采用冒泡排序的方式)

#include <stdio.h>
#include <stdlib.h>

// 根据不同的数据类型,自己编写不同的回调函数,进行数据比较
//  n1 > n2,返回值 >0
//  n1 = n2,返回值 =0
//  n1 = n2,返回值 <0
int int_cmp(const void* n1, const void* n2) {
    return *(int*)n1 - *(int*)n2;
}

// 按字节进行数据交换
void swap(void* n1, void* n2, int width) {
    int i = 0;
    // 非法输入
    if (n1 == NULL || n2 == NULL) {
        exit(1);
    }
    for (; i < width; i++) {
        char tmp = *((char*)n1+i);
        *((char*)n1 + i) = *((char*)n2 + i);
        *((char*)n2 + i) = tmp;
    }
}

// arr : 待排序数组首元素
// len : 数组长度
// width : 数组元素宽度(元素类型所占字节数)
// int (*cmp)(void*, void*) : 一个参数为(void*, void*) 返回值为 int 的函数指针
void bubble_sqort(void* arr, int len, int width, int(*cmp)(void*, void*)) {
    int i = 0;
    // 进行冒泡
    for (; i < len - 1; i++) {
        int j = i;
        for (; j < len - 1; j++) {
            if (cmp((char*)arr + j*width, (char*)arr + (j + 1)*width) > 0) {
                swap((char*)arr + j*width, (char*)arr + (j + 1)*width, width);
            }
        }
    }
}

int main() {
    int arr[] = { 1, 2, 6, 4, 2, 7, 4, 6, 3, 8, 9, 5 };
    int i = 0;

    bubble_sqort(arr, sizeof(arr) / sizeof(arr[0]), sizeof(int), int_cmp);

    // 打印排序后的数组
    for (; i < sizeof(arr) / sizeof(arr[0]); i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    system("pause");
    return 0;
}

  运行结果:

运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值