目录
总结:以上就是今天要讲的内容,本文简单介绍了回调函数的定义和使用。当然回调函数的应用场景并不是那么广泛,但有这么个概念肯定是有它的作用。就比如能让我们更轻松的理解代码。
前言
本篇文章我将会介绍回调函数概念。
一、回调函数是什么?
说白了,回调函数就是使用函数不直接使用像< funtion();>这样的形式,而是创建一个函数指针,用指针来调用该函数。
接下来我用代码来将其实例化:
#include <stdio.h>
int sub(int x, int y)
{
return x - y;
}
int compair(int a, int b)
{
//在compair中通过p_sub来实现回调函数
if (a > b)
return p_sub(a, b);
else
return p_sub(b, a);
}
int main()
{
int a = 4;
int b = 2;
//用p_sub指针来指向sub函数
int (*p_sub)(int, int) =⊂
int ret = compair(a,b);
//此时ret得到的是a与b之差的绝对值
return 0;
}
在上述代码中我用p_sub函数指针来存放sub函数地址(当然sub前可以不加&,为了更易理解便加上罢),然后在compair中通过使用p_sub来间接使用sub函数,以上便实现了回调函数。
值得注意的是:回调函数是一个类似于说法之类的概念,不能跟像是函数,数组之类的定义混为一谈。
二、使用回调函数,模拟实现qsort(采用冒泡的方式)。
#include <stdio.h>
int int_cmp(const void* p1, const void* p2)
{
return (*(int*)p1 - *(int*)p2);
}
void _swap(void* p1, void* p2, int size)
{
int i = 0;
for (i = 0; i < size; i++)
{
char tmp = *((char*)p1 + i);
*((char*)p1 + i) = *((char*)p2 + i);
*((char*)p2 + i) = tmp;
}
}
//排序函数主体
void bubble(void* base, int count, int size, int(*cmp)(void*, void*))
{
int i = 0;
int j = 0;
for (i = 0; i < count - 1; i++)
{
for (j = 0; j < count - i - 1; j++)
{
if (cmp((char*)base + j * size, (char*)base + (j + 1) * size) > 0)
{
_swap((char*)base + j * size, (char*)base + (j + 1) * size, size);
}
}
}
}
int main()
{
int arr[] = { 1, 3, 5, 7, 9, 2, 4, 6, 8, 0 };
//char *arr[] = {"aaaa","dddd","cccc","bbbb"};
int i = 0;
//
bubble(arr, sizeof(arr) / sizeof(arr[0]), sizeof(int), int_cmp);
//打印排序后的数组
for (i = 0; i < sizeof(arr) / sizeof(arr[0]); i++)
{
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
263




被折叠的 条评论
为什么被折叠?



