函数指针

来源:互联网 发布:流体热力学软件 编辑:程序博客网 时间: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
原创粉丝点击