C语言的回调函数
来源:互联网 发布:k近邻算法 编辑:程序博客网 时间:2024/04/29 04:43
C语言的回调函数:
中心思想
将一个函数作为形式参数传递到另外一个函数中去。通过函数指针去调用另外一个函数。回调函数都是在其他地方通过函数指针来进行回调;
相关性:
1. 回调函数跟函数指针相关
2. 其它函数不需要知道回调函数的具体逻辑
优点
这样的函数指针可以降低函数与函数之间的耦合度
回调函数的概念:
1:回调函数就是通过函数指针调用的函数
2:把函数指针作为参数传递给另外一个函数,当这个指针被用来调用其所指向的函数时,我们就说是回调函数
3:回调函数不是由该函数的实现方直接进行调用,而是在特定的事件或者条件下另外一方调用,用于该事件或条件进行相应。
回调函数流程
1:定义一个回调函数
2:提供函数的调用方在初始化的时候,将回调函数的函数指针传递给调用者
3:当特定事件或者条件发生的时候,调用者使用函数指针所指向的函数对事件进行处理;
优点
1:提高代码的通用性
2:降低函数之间的耦合性
重点
回调函数的整体思想是最重要的
上面概念性的东西太多了,其实回调函数通俗一点来说,就是函数监听法,即我赋予了你一个执行某项函数的权利,当我需要拿到某个东西的时候。你去执行,执行完了再把结果返回给我,这样的一个过程叫做回调过程。比如说,一个按键只有在点击的时候才会去做触发。
out_print.h
#ifndef __OUT_PRINT_H#define __OUT_PRINT_Hvoid out_print(int *p,int n); #endif
out_print.c
#include"out_print.h"#include<stdio.h>void out_print(int* pointer,int n){ int i = 0; for(i = 0; i < n;i++){ printf("num:%d,value:%d\n",i+1,*(pointer+i)); } }
sort_utils.h
#ifndef __SORT_UTILS_H#define __SORT_UTILS_H/** *冒泡排序法 */void bubble_sort(int*,int);/** *选择排序法 */void select_sort(int*,int);#endif
sort_utils.c
#include"sort_utils.h"#include<stdio.h>void bubble_sort(int* pointer,int n){ int i,j; for(i = 0; i< n -1; i++){ for(j = n-1;j>i;j--){ if(*(pointer+j) < *(pointer+j-1)){ int temp ; temp = *(pointer+j); *(pointer+j) = *(pointer+j-1); *(pointer+j-1) = temp; } } } }void select_sort(int* pointer,int n){ int i,j; for(i = 0;i<n-1;i++){ int pos = i; for(j = i+1 ;j <n ;j++){ if(*(pointer+j)<*(pointer+pos)){ pos = j; } } if(pos != i){ int temp; temp = *(pointer +pos); *(pointer+pos) = *(pointer+i); *(pointer+i) = temp; } } }
out_data.c
void out_arraydata(int* pointer,int n,void (*pointer1)(int *,int),void *(pointer2)(int *,int)){ pointer1(pointer,n); pointer2(pointer,n);}
mainTest.c
#include<stdio.h>#include"sort_utils.h"#include"out_print.h"int main(int argc,char * argv[]){ int bubble_array [] = {13,2,4,1,8,9,15,7}; out_arraydata(bubble_array,8,bubble_sort,out_print); int select_array [] = {7,2,5,3,8,13,35,65,1}; out_arraydata(select_array,8,select_sort,out_print); return 0;}
输出的结果为:
num:1,value:1
num:2,value:2
num:3,value:4
num:4,value:7
num:5,value:8
num:6,value:9
num:7,value:13
num:8,value:15
num:1,value:2
num:2,value:3
num:3,value:5
num:4,value:7
num:5,value:8
num:6,value:13
num:7,value:35
num:8,value:65
- 学习C语言的回调函数
- C语言回调函数的学习
- 学习C语言的回调函数
- C语言回调函数的学习
- C语言的回调函数
- C语言回调函数的使用
- C语言的回调函数
- C语言---回调函数
- c语言回调函数
- c语言回调函数
- C语言回调函数
- C语言回调函数
- C语言回调函数
- C语言回调函数
- 回调函数(c语言)
- C语言--回调函数
- C语言回调函数
- C语言回调函数
- 浅谈JavaScript实现可视化展示冒泡排序过程
- 百度一下 自动提示 js
- 使用redis如何实现动态时间段内统计排序?
- 数据结构python实现简单Stack
- 学习数据结构与算法 第一天
- C语言的回调函数
- 长公式处理方法
- 链表有点难
- JavaScript的with语句、switch语句及函数
- 关于Ubuntu下的PDF阅读器
- 关于网络受限的几种解决办法
- bzoj 3876: [Ahoi2014]支线剧情 (无源汇最小费用可行流)[省选计划系列]
- 表单自动验证 js
- Vue 之数组