函数指针是指向函数的指针,可以用来做回调函数,也可以做函数的一个参数。其声明方法是:
比如:
注意,分清
函数指针
与
返回类型是指针的函数
的区别 !
返回类型是指针的函数举例:
- int * func(int a, int b);
下面是一个具体的例子,
----
-
-
-
-
-
- #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));
- printf("%d\n", compute(subtract, 5, 6));
-
- return 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()的定义:
-
-
- 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 *);
符合我们开头提到的函数指针的声明方法: