一、前言
回调函数是要利用指针实现比较复杂的内容,写成的代码都比较复杂
二、回调函数基本知识
回调函数:回调函数就是一个通过函数指针调用的函数。如果你把函数的指针(地址)作为参数传递给另一个函数,当这个指针被用来调用其所指向的函数时,我们就说这是回调函数。回调函数不是由该函数的实现方直接调用,而是在特定的事件或条件发生时由另外的一方调用的,用于对该事件或条件进行晌应。
回调函数的常见用法:计算器
三、回调函数的冒泡排序
我们根据之前学习的知识已经不难写出冒泡排序,但是这种冒泡排序不具备很好的通用性,这时候我们的回调函数则能改变其通用性。
#define _CRT_SECURE_NO_WARNINGS 1
#pragma warning(disable:6031)
#include <stdio.h>
void Swap( char* buf1, char* buf2,int width)
{
int i = 0;
for (i = 0; i < width; i++)
{
char tmp = *buf1;
*buf1 = *buf2;
*buf2 = tmp;
buf1++;
buf2++;
}
}
void bubble_sort(void* base,int width,int sz,int(*cmp)(void* e1,void* e2))
{
int i = 0;
for (i = 0; i < sz - 1; i++)
{
int j = 0;
for (j = 0; j < sz - 1 - i; j++)
{
if(cmp((char*)base+j*width,(char*)base+(j+1)*width)>0)
{
Swap((char*)base + j * width, (char*)base + (j + 1) * width, width);
}
}
}
}
int cmp_int(const void* e1,const void* e2)
{
return(*(int*)e1-*(int*)e2);
}
int cmp_stu_by_age(const void* e1,const void* e2)
{
return ((struct Stu*)e1)->age- ((struct Stu*)e2)->age;
}
struct Stu
{
char name[20];
int age[10];
};
int test1()
{
int arr[10] = { 0,1,2,3,4,5,6,7,8,9 };
int sz = sizeof(arr)/sizeof(arr[0]);
bubble_sort(arr,sizeof(arr[0]),sz,cmp_int);
}
int test2()
{
struct Stu s[3] = { {"zhangsan",18} ,{"lisi",20} ,{"wangwu",30}};
int sz = sizeof(s)/sizeof(s[0]);
bubble_sort(s,sizeof(s[0]), sz, cmp_stu_by_age);
}
int main()
{
test1();
test2();
return 0;
}
补充:
void* 类型的指针 可以接收任意类型的地址
但是我们void*类型的指针 不能进行解引用操作,不能进行±整数的操作
补充:
bubble_sort(void* base,int width,int sz,int(cmp)(void e1,void* e2))中
第一个参数是接收首元素的地址
第二个参数是元素个数
第三个参数是单个元素的大小
第四个参数是函数指针——不同元素的比较方法是不同的,我们将比较方法写成函数抽离出来
重点关注:
自定义函数bubble_sort第四个参数是函数指针,利用回调函数判断是否需要交换
这个回调函数的参数设计,宽度传过去这样设计能够处理不同类型的的数据
Swap函数中width次循环的原因:
Swap函数定义中形参就是字符指针,所以需要width次循环
四、总结
这个代码是比较复杂的,希望大家指出不足