[good]c语言函数指针的运用
#include <stdio.h> #define MAX 10 void swap(int *x, int *y) { int temp; temp = *x; *x = *y; *y = temp; } void fun(int *height, int *age) { int n = 10; *height = n * 10; *age = n * 2000; } int *createArray(int size) { int i; int *arr = (int *)(malloc(sizeof(int) * size)); for (i = 0; i < size; i++) { arr[i] = i * i; } return arr; } int *sumArray(int arr) { return 0; } int add(int x, int y) { return x + y; } int substract(int x, int y) { return x - y; } int multiply(int x, int y) { return x * y; } int divide(int x, int y) { return x / y; } int module(int x, int y) { return x % y; } typedef int (*operation_fun)(int, int); void main() { int num = 0; int (*ptr_add)(int, int) = add; void (*ptr_swap)(int, int) = swap; int a = 100, b = 200; int sum = ptr_add(a, b); printf("the result is %d\n", sum); ptr_swap(&a, &b); printf("before swap a is %d, b is %d\n", a, b); swap(&a, &b); printf("after swap a is %d, b is %d\n", a, b); operation_fun operations[] = { &add, &substract, &multiply, ÷, &module}; // int (*operations[])(int, int) = {add, substract, multiply, divide, module}; // int (*operations[])(int, int) = {&add, &substract, &multiply, ÷, &module}; char *arr[] = {"add", "substract", "multiply", "divide", "module"}; int result = 0; int i, j; for (i = 0; i < 5; i++) { result = operations[i](10, 20); printf("%s of two number result is %d\n", arr[i], result); } int p_height; int p_age; fun(&p_height, &p_age); printf("height is %d and age is %d\n", p_height, p_age); int c = 30; int *ptr1 = &c; int **ptr2 = &ptr1; printf("c is %d\n", c); printf("ptr1 is %d\n", *ptr1); printf("ptr2 is %d\n", **ptr2); }
是的,在一个函数里面调用另一个函数可以使用函数指针。这种方式常常用于实现回调函数的模式。下面是一个例子:
假设我们有一个函数 compute
, 它接受两个整数和一个函数指针作为参数。这个函数指针指向的函数也接受两个整数作为参数,并返回一个整数。compute
函数将两个整数传递给函数指针指向的函数,并返回计算的结果。
在这个例子中,compute
函数通过函数指针 op
调用了 add
和 subtract
函数。这展示了如何在一个函数内部通过函数指针调用另一个函数。
是的,你完全可以在定义函数指针类型时省略参数名,只保留参数类型。这是因为在定义函数指针类型时,参数名并不重要,重要的是参数类型和数量。
所以,你可以这样定义函数指针类型:
```c
typedef int (*operation)(int, int);
```
这将定义一个名为 `operation` 的函数指针类型,该类型的函数接受两个 `int` 参数并返回一个 `int`。你可以使用这个类型来声明函数指针,例如:
```c
operation add, subtract;
```
然后,你可以将指向相应函数的指针赋值给这些函数指针,例如:
```c
add = &add_function;
subtract = &subtract_function;
```
其中 `add_function` 和 `subtract_function` 是你定义的接受两个 `int` 参数并返回一个 `int` 的函数。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
2021-11-29 vim的使用技巧