C基础知识(6):指针--函数指针与回调涵数
2024-09-03 21:36:30
函数指针
函数指针是指向函数的指针变量。
通常我们说的指针变量是指向一个整型、字符型或数组等变量,而函数指针是指向函数。
函数指针可以像一般函数一样,用于调用函数、传递参数。
#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();
}
最新文章
- 使用Java判断字符串中的中文字符数量
- GDI与GDI+ 贴图性能对比
- LINQ 联表查询 取count 值
- LA 2678 Subsequence(二分查找)
- pstack使用和原理
- dwz ie10一直提示数据加载中
- [Java] 识别图片验证码
- Android ScrollView+ViewPager+PullToRefreshListView
- PL/SQL:使用pragma restrict_references限制包权限
- FusionChart学习笔记(部分)
- runtime 运行时机制 完全解读
- 数据库出现1045 access denied for user &#39;root&#39;@&#39;localhost&#39; using password yes (转)
- C#中的DBNull、Null、""和String.Empty
- template.helper()方法
- Dynamics 365 for CRM: Sitemap站点图的可视化编辑功能
- docker报Error response from daemon: client is newer than server (client API version: 1.24, server API version: 1.19)
- [Tensorflow] RNN - 01. Spam Prediction with BasicRNNCell
- Integer类之缓存
- 修改apache配置文件去除thinkphp url中的index.php(转)
- Cousera 无法播放视频 解决办法 widows 和 linux
热门文章
- TCP的ACK原理和延迟确认机制
- JS 对浏览器相关的操作
- git clone报错error: RPC failed; curl 18 transfer closed with outstanding read data remaining
- django之表多对多建立方式、form组件、钩子函数 08
- Error from server (NotFound): the server could not find the requested resource (get services http:heapster:)
- Vue(js框架)
- python 访问列表中的值
- selenium 与appium的关系
- LibreOffice/Calc:在表格中始终显示某列/某行
- CDOJ 1264 人民币的构造 区间问题+数论