c 函数作为参数
时间: 2023-12-19 11:07:04 浏览: 20
C语言中可以将函数作为参数传递给另一个函数。这种函数被称为回调函数,它可以增强函数的灵活性和可重用性。回调函数的原理是将函数名作为参数传递给另一个函数,并在需要时通过该函数名来调用函数。
例如,以下是一个简单的示例,其中函数print_array接受一个整数数组和一个指向回调函数的指针作为参数,并使用回调函数来打印数组中的每个元素:
```
#include <stdio.h>
void print_array(int arr[], int size, void (*callback)(int)) {
for (int i = 0; i < size; i++) {
callback(arr[i]);
}
}
void print_element(int element) {
printf("%d ", element);
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
print_array(arr, size, print_element);
return 0;
}
```
在上面的示例中,我们定义了两个函数:print_array和print_element。print_array接受一个整数数组、数组大小和一个指向回调函数的指针作为参数。它使用回调函数来遍历数组并打印每个元素。print_element是回调函数,它接受一个整数作为参数并将其打印到控制台上。
在main函数中,我们首先定义一个整数数组arr,然后使用sizeof运算符计算数组大小,并将数组、大小和回调函数print_element作为参数传递给print_array函数。print_array函数使用回调函数print_element来打印数组中的每个元素。
输出结果为:1 2 3 4 5
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)