20161127

函数指针是指向函数的指针,可以用来做回调函数,也可以做函数的一个参数。其声明方法是:

[cpp]  view plain  copy
  1. 函数类型 (标志符指针变量名) (形参列表);  
比如:

[cpp]  view plain  copy
  1. int (*fp)(int a, int b);  
注意,分清 函数指针 返回类型是指针的函数 的区别 !

返回类型是指针的函数举例:

[cpp]  view plain  copy
  1. int * func(int a, int b);  

下面是一个具体的例子,

----

[cpp]  view plain  copy
  1. /** 
  2.  * reference : http://en.wikipedia.org/wiki/Function_pointer 
  3.  * 
  4.  */  
  5.   
  6. #include <stdio.h>  
  7. #include <stdlib.h>  
  8.   
  9. typedef int(*fp_operation)(int a, int b);  
  10.   
  11. int add(int a, int b);  
  12. int subtract(int a, int b);  
  13. int compute(fp_operation op, int a, int b);  
  14.   
  15. int main() {  
  16.     printf("%d\n", compute(add, 5, 6)); // 11  
  17.     printf("%d\n", compute(subtract, 5, 6)); // -1  
  18.   
  19.     return 0;  
  20. }  
  21.   
  22. int add(int a, int b) {  
  23.     return a+b;  
  24. }  
  25.   
  26. int subtract(int a, int b) {  
  27.     return a-b;  
  28. }  
  29.   
  30. int compute(fp_operation operation, int num1, int num2) {  
  31.     return operation(num1, num2);  
  32. }  

另一个常见的函数指针的例子是qsort():

[cpp]  view plain  copy
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3.   
  4. int comp(int *a, int *b) {  
  5.     return *a > *b;  
  6. }  
  7.   
  8. int main(int argc, char *argv[]) {  
  9.     int i, s[] = { 1, 3, 12, 5 };  
  10.   
  11.     /* 声明一个函数指针,它指向一个函数 */  
  12.     int (*fp)() = comp;  
  13.   
  14.     qsort(s, 4, sizeof(int), fp);  
  15.   
  16.     for (i = 0; i < 4; i++) {  
  17.         printf("%d,", s[i]);  
  18.     }  
  19.     return 0;  
  20. }  

查看qsort()的定义:

[cpp]  view plain  copy
  1. /* Sort NMEMB elements of BASE, of SIZE bytes each, 
  2.    using COMPAR to perform the comparisons.  */  
  3. extern void qsort (void *__base, size_t __nmemb, size_t __size,  
  4.            __compar_fn_t __compar) __nonnull ((1, 4));  

其中的 __compar_fn_t   是函数指针,定义为:

[cpp]  view plain  copy
  1. typedef int (*__compar_fn_t) (__const void *, __const void *);  

符合我们开头提到的函数指针的声明方法:

[cpp]  view plain  copy
  1. 函数类型 (标志符指针变量名) (形参列表);  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值