函数指针
来源:互联网 发布:流体热力学软件 编辑:程序博客网 时间:2024/04/30 11:39
函数指针是指向函数的指针,可以用来做回调函数,也可以做函数的一个参数。其声明方法是:
函数类型 (标志符指针变量名) (形参列表);比如:
int (*fp)(int a, int b);注意,分清函数指针与返回类型是指针的函数的区别 !
返回类型是指针的函数举例:
int * func(int a, int b);
下面是一个具体的例子,
----
/** * reference : http://en.wikipedia.org/wiki/Function_pointer * */#include <stdio.h>#include <stdlib.h>typedef int(*fp_operation)(int a, int b);int add(int a, int b);int subtract(int a, int b);int compute(fp_operation op, int a, int b);int main() {printf("%d\n", compute(add, 5, 6)); // 11printf("%d\n", compute(subtract, 5, 6)); // -1return 0;}int add(int a, int b) {return a+b;}int subtract(int a, int b) {return a-b;}int compute(fp_operation operation, int num1, int num2) {return operation(num1, num2);}
另一个常见的函数指针的例子是qsort():
#include <stdio.h>#include <stdlib.h>int comp(int *a, int *b) {return *a > *b;}int main(int argc, char *argv[]) {int i, s[] = { 1, 3, 12, 5 };/* 声明一个函数指针,它指向一个函数 */int (*fp)() = comp;qsort(s, 4, sizeof(int), fp);for (i = 0; i < 4; i++) {printf("%d,", s[i]);}return 0;}
查看qsort()的定义:
/* Sort NMEMB elements of BASE, of SIZE bytes each, using COMPAR to perform the comparisons. */extern void qsort (void *__base, size_t __nmemb, size_t __size, __compar_fn_t __compar) __nonnull ((1, 4));
其中的__compar_fn_t 是函数指针,定义为:
typedef int (*__compar_fn_t) (__const void *, __const void *);
符合我们开头提到的函数指针的声明方法:
函数类型 (标志符指针变量名) (形参列表);----
EOF
0 0
- 指针函数 函数指针
- 函数指针/指针函数
- 指针函数&函数指针
- 函数指针 指针函数
- 函数指针 指针函数
- 指针函数,函数指针
- 函数指针,指针函数,
- 指针函数,函数指针
- 函数指针 指针函数
- 函数指针、指针函数
- 指针函数&函数指针
- 函数指针 指针函数
- 函数指针 指针函数
- 函数指针&指针函数
- 指针函数 函数指针
- 指针函数 &函数指针
- 函数指针&指针函数
- void指针 函数指针
- 多线程编程12-----CyclicBarrier同步工具类
- Oracle 实现按周、月、季度、年查询统计数据
- androidpn消息下推2
- ActiveMQ In Action 第二章 理解面向对象的中间件(MOM)和JMS 2.4 JMS规范
- 通过smali调试android APK
- 函数指针
- 发送短信成功
- ASP.NET动态数据网站实战
- ajax请求webservice错误Request format is invalid: application/json;utf-8
- 多线程编程13-----Exchanger同步工具类实现两线程数据交换
- 自动化测试实施步骤和最佳实践
- Unity3D学习笔记 Perfab
- cocos2dx 让一个滚动层跟着另一个动
- UML之轻松入门(1)-类图