C一级函数指针形参和二级函数指针形参,如何使用?分别举例说明
时间: 2024-10-01 11:01:50 浏览: 54
在C语言中,一级函数指针和二级函数指针都是用来作为函数的参数或者返回值,以便动态地传递或调用函数。
**一级函数指针形参**:
一级函数指针是一个指向函数地址的变量。它用于接收一个特定类型的函数作为输入。例如:
```c
#include <stdio.h>
// 定义一个返回整数并接受两个整数的函数
int add(int a, int b) {
return a + b;
}
void function_with_function_ptr(int (*func)(int, int), int arg1, int arg2) {
// 调用传入的函数,并打印结果
printf("Result: %d\n", func(arg1, arg2));
// 使用一级函数指针直接调用add函数
printf("Add result: %d\n", func(add, 5, 7)); // 此处add被当作一级函数指针传递
}
int main() {
function_with_function_ptr(add, 3, 4); // 通过函数名作为一级函数指针传递
return 0;
}
```
在这个例子中,`function_with_function_ptr`函数接受一个`int(*)`类型的形参`func`,它可以指向任何接受两个`int`参数并返回`int`的函数。
**二级函数指针形参**:
二级函数指针则是指向一级函数指针的指针。这允许我们存储不同类型的一级函数指针,然后根据需要调用它们。例如:
```c
#include <stdio.h>
typedef int(*FuncTypeOne)(int, int);
typedef int(*FuncTypeTwo)(char, char);
void function_with二级_function_ptr(FuncTypeOne primary_func_ptr, FuncTypeTwo secondary_func_ptr) {
printf("First Function Result: %d\n", primary_func_ptr(5, 6)); // 使用一级函数指针
printf("Second Function Result: %d\n", secondary_func_ptr('a', 'b')); // 使用二级函数指针间接调用
}
int add(int a, int b) {
return a + b;
}
char compare(char c1, char c2) {
return (c1 > c2) ? 1 : -1;
}
int main() {
function_with二级_function_ptr(add, compare); // 传递两个不同类型的函数指针
return 0;
}
```
在这里,`function_with二级_function_ptr`函数接受两个二级函数指针,`primary_func_ptr`和`secondary_func_ptr`,可以分别指向`FuncTypeOne`和`FuncTypeTwo`类型的函数。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)