107 lines
2.1 KiB
Markdown
107 lines
2.1 KiB
Markdown
1. **函数指针示例**:
|
|
|
|
```c
|
|
#include <stdio.h>
|
|
|
|
int add(int a, int b) {
|
|
return a + b;
|
|
}
|
|
|
|
int main() {
|
|
// 声明函数指针
|
|
int (*ptr_add)(int, int);
|
|
|
|
// 将 add 函数的地址赋值给函数指针
|
|
ptr_add = add;
|
|
|
|
// 通过函数指针调用函数
|
|
int result = ptr_add(5, 3);
|
|
printf("Result: %d\n", result); // 输出: Result: 8
|
|
|
|
return 0;
|
|
}
|
|
```
|
|
|
|
2. **指针函数示例**:
|
|
|
|
```c
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
|
|
int* allocate_array(int size) {
|
|
// 动态分配内存并返回指针
|
|
return (int*)malloc(size * sizeof(int));
|
|
}
|
|
|
|
int main() {
|
|
// 调用指针函数获取动态分配的数组
|
|
int* arr = allocate_array(5);
|
|
|
|
// 使用动态分配的数组
|
|
for (int i = 0; i < 5; i++) {
|
|
arr[i] = i * 2;
|
|
printf("%d ", arr[i]);
|
|
}
|
|
printf("\n"); // 输出: 0 2 4 6 8
|
|
|
|
// 释放动态分配的内存
|
|
free(arr);
|
|
|
|
return 0;
|
|
}
|
|
```
|
|
|
|
3. **回调函数示例**:
|
|
|
|
```c
|
|
#include <stdio.h>
|
|
|
|
// 回调函数的类型定义
|
|
typedef int (*CompareFn)(int, int);
|
|
|
|
// 使用回调函数的排序函数
|
|
void sort_array(int arr[], int size, CompareFn compare_fn) {
|
|
for (int i = 0; i < size - 1; i++) {
|
|
for (int j = 0; j < size - i - 1; j++) {
|
|
if (compare_fn(arr[j], arr[j+1]) > 0) {
|
|
// 使用回调函数比较元素大小
|
|
int temp = arr[j];
|
|
arr[j] = arr[j+1];
|
|
arr[j+1] = temp;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// 升序比较函数
|
|
int compare_ascending(int a, int b) {
|
|
return a - b;
|
|
}
|
|
|
|
// 降序比较函数
|
|
int compare_descending(int a, int b) {
|
|
return b - a;
|
|
}
|
|
|
|
int main() {
|
|
int numbers[] = {5, 2, 8, 1, 9};
|
|
int size = sizeof(numbers) / sizeof(numbers[0]);
|
|
|
|
printf("Ascending sort:\n");
|
|
sort_array(numbers, size, compare_ascending);
|
|
for (int i = 0; i < size; i++) {
|
|
printf("%d ", numbers[i]); // 输出: 1 2 5 8 9
|
|
}
|
|
printf("\n");
|
|
|
|
printf("Descending sort:\n");
|
|
sort_array(numbers, size, compare_descending);
|
|
for (int i = 0; i < size; i++) {
|
|
printf("%d ", numbers[i]); // 输出: 9 8 5 2 1
|
|
}
|
|
printf("\n");
|
|
|
|
return 0;
|
|
}
|
|
```
|