函数指针

函数指针是指向函数的指针变量

通常我们说的指针变量是指向一个整型、字符型或数组等变量,而函数指针是指向函数。

函数指针可以像一般函数一样,用于调用函数、传递参数。

 #include <stdio.h>

 // 取两个数里最大的数字
int getMaxValue(int, int); int main() {
// func就是涵数指针
int (*p)(int, int) = &getMaxValue; // &可省略
int a = , b = , c = , d;
d = p(c, p(a, b));
printf("%d\n", d); //
return ;
} int getMaxValue(int x, int y) {
return x >= y ? x : y;
}

回调涵数

函数指针变量可以作为某个函数的参数来使用的,回调函数就是一个通过函数指针调用的函数。

简单讲:回调函数是由别人的函数执行时调用你实现的函数。

 #include <stdio.h>
#include <stdlib.h> // 回调函数
void populateArray(int *arr, size_t size, int (*getNextValue)(void));
// 获取随机值
int getNextRandomValue(); int main() {
int arr[], i;
populateArray(arr, , getNextRandomValue);
for (i = ; i < ; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return ;
}
// size_t 是一种数据类型,近似于无符号整型,但容量范围一般大于 int 和 unsigned
// int (*getNextValue)(void) = getNextRandomValue; (涵数指针)
void populateArray(int *arr, size_t size, int (*getNextValue)(void)) {
size_t i;
for (i = ; i < size; i++) {
arr[i] = getNextValue();
}
}
int getNextRandomValue() {
return rand();
}

最新文章

  1. 使用Java判断字符串中的中文字符数量
  2. GDI与GDI+ 贴图性能对比
  3. LINQ 联表查询 取count 值
  4. LA 2678 Subsequence(二分查找)
  5. pstack使用和原理
  6. dwz ie10一直提示数据加载中
  7. [Java] 识别图片验证码
  8. Android ScrollView+ViewPager+PullToRefreshListView
  9. PL/SQL:使用pragma restrict_references限制包权限
  10. FusionChart学习笔记(部分)
  11. runtime 运行时机制 完全解读
  12. 数据库出现1045 access denied for user &#39;root&#39;@&#39;localhost&#39; using password yes (转)
  13. C#中的DBNull、Null、""和String.Empty
  14. template.helper()方法
  15. Dynamics 365 for CRM: Sitemap站点图的可视化编辑功能
  16. docker报Error response from daemon: client is newer than server (client API version: 1.24, server API version: 1.19)
  17. [Tensorflow] RNN - 01. Spam Prediction with BasicRNNCell
  18. Integer类之缓存
  19. 修改apache配置文件去除thinkphp url中的index.php(转)
  20. Cousera 无法播放视频 解决办法 widows 和 linux

热门文章

  1. TCP的ACK原理和延迟确认机制
  2. JS 对浏览器相关的操作
  3. git clone报错error: RPC failed; curl 18 transfer closed with outstanding read data remaining
  4. django之表多对多建立方式、form组件、钩子函数 08
  5. Error from server (NotFound): the server could not find the requested resource (get services http:heapster:)
  6. Vue(js框架)
  7. python 访问列表中的值
  8. selenium 与appium的关系
  9. LibreOffice/Calc:在表格中始终显示某列/某行
  10. CDOJ 1264 人民币的构造 区间问题+数论