C语言函数指针的六个高级应用-(进阶)

概述 

       函数指针是一种非常强大的编程工具,它可以让我们以更加灵活的方式编写程序。在本文中,我们将介绍 8 个函数指针的高级应用场景,并贴出相应的代码案例和解释。

  • 回调函数

回调函数是指在某个事件发生时被调用的函数。通常,回调函数是在某个库函数或框架函数中注册的,当某个条件满足时,库函数或框架函数会调用回调函数来执行相应的操作。以下是一个示例:

#include <stdio.h>

void handle_event(int event_type, void (*callback)(void)) {
    printf("event %d occurred\n", event_type);
    if (callback) {
        callback();
    }
}

void callback_function() {
    printf("callback function called\n");
}

int main() {
    handle_event(1, callback_function);
    handle_event(2, NULL);
    return 0;
}

        在上面的代码中,我们定义了一个 handle_event 函数,它接受两个参数:一个事件类型和一个函数指针。如果函数指针不为空,则会调用指定的函数。在 main 函数中,我们分别调用 handle_event 函数来触发两个事件,其中第一个事件注册了一个回调函数 callback_function,第二个事件没有注册回调函数。

  • 函数参数化

函数参数化是指通过函数指针将函数的某些行为参数化。这样,我们可以在调用函数时动态地指定函数的行为。以下是一个示例:

#include <stdio.h>

void process_array(int *array, size_t size, int (*process)(int)) {
    for (size_t i = 0; i < size; i++) {
        array[i] = process(array[i]);
    }
}

int increment(int n) {
    return n + 1;
}

int main() {
    int array[] = {1, 2, 3, 4, 5};
    size_t size = sizeof(array) / sizeof(int);
    process_array(array, size, increment);
    for (size_t i = 0; i < size; i++) {
        printf("%d ", array[i]);
    }
    printf("\n");
    return 0;
}

        在上面的代码中,我们定义了一个 process_array 函数,它接受三个参数:一个整型数组、数组大小和一个函数指针。函数指针指向一个函数,该函数接受一个整型参数并返回一个整型结果。在 process_array 函数中,我们将数组中的每个元素传递给指定的函数,然后将函数的返回值存储回原数组中。在 main 函数中,我们定义了一个 increment 函数,它将传入的整数加 1。然后,我们调用 process_array 函数来处理整型数组,并打印出结果。

  • 排序算法

排序算法是函数指针的另一个常见应用场景。通过传递不同的比较函数,我们可以在不同的排序算法中重用相同的代码。以下是一个示例:

#include <stdio.h>
#include <stdlib.h>

typedef int (*compare_func_t)(const void *, const void *);

void sort(int *array, size_t size, compare_func_t compare_func) {
    qsort(array, size, sizeof(int), compare_func);
}

int compare_int(const void *a, const void *b) {
    return (*(int*)a - *(int*)b);
}

int compare_reverse_int(const void *a, const void *b) {
    return (*(int*)b - *(int*)a);
}

int main() {
    int array[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
    size_t size = sizeof(array) / sizeof(int);
    sort(array, size, compare_int);
    for (size_t i = 0; i < size; i++) {
        printf("%d ", array[i]);
    }
    printf("\n");
    sort(array, size, compare_reverse_int);
    for (size_t i = 0; i < size; i++) {
        printf("%d ", array[i]);
    }
    printf("\n");
    return 0;
}

        在上面的代码中,我们定义了一个 sort 函数,它接受三个参数:一个整型数组、数组大小和一个比较函数指针。比较函数指针指向一个函数,该函数接受两个指向常量 void 类型的指针,并返回一个整型结果。在 sort 函数中,我们使用标准库函数 qsort 来对整型数组进行排序,其中比较函数指针由调用者传递。

在 main 函数中,我们定义了两个比较函数 compare_int 和 compare_reverse_int,分别用于升序和降序排序。然后,我们调用 sort 函数来对整型数组进行排序,并打印出结果。

  • 函数指针数组

        函数指针数组是指一个数组,其中的每个元素都是一个函数指针。这种数组可以用于实现一个分派表,根据输入参数的不同,动态地调用不同的函数。以下是一个示例:

#include <stdio.h>

void add(int a, int b) {
    printf("%d + %d = %d\n", a, b, a + b);
}

void subtract(int a, int b) {
    printf("%d - %d = %d\n", a, b, a - b);
}

void multiply(int a, int b) {
    printf("%d * %d = %d\n", a, b, a * b);
}

void divide(int a, int b) {
    if (b == 0) {
        printf("cannot divide by zero\n");
    } else {
        printf("%d / %d = %d\n", a, b, a / b);
    }
}

typedef void (*operation_func_t)(int, int);

int main() {
    operation_func_t operations[] = {add, subtract, multiply, divide};
    size_t num_operations = sizeof(operations) / sizeof(operation_func_t);
    int a = 10, b = 5;
    for (size_t i = 0; i < num_operations;i++)
    {
    	operations[i](a,b);
    }
  	return 0;
}

        在上面的代码中,我们定义了四个函数 add、subtract、multiply 和 divide,分别对两个整数进行加、减、乘和除操作。

然后,我们定义了一个函数指针类型 operation_func_t,它指向一个接受两个整型参数并没有返回值的函数。接着,我们定义了一个函数指针数组 operations,其中的每个元素都是一个 operation_func_t 类型的函数指针,分别指向 add、subtract、multiply 和 divide 函数。

在 main 函数中,我们使用 for 循环遍历 operations 数组,并依次调用每个函数指针所指向的函数。在每次调用函数之前,我们可以根据需要设置 a 和 b 的值。这样,我们就可以动态地选择要执行的操作。

  • 函数指针与回溯法

        回溯法是一种求解一些组合优化问题的算法,它通常使用递归来实现。函数指针可以用于实现回溯法算法的一些关键部分。

以下是一个使用回溯法来计算排列的示例:

#include <stdio.h>
#include <stdlib.h>

typedef void (*callback_func_t)(const int *, size_t);

void swap(int *a, int *b) {
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

void permute(int *nums, size_t len, size_t depth, callback_func_t callback) {
    if (depth == len) {
        callback(nums, len);
        return;
    }
    for (size_t i = depth; i < len; i++) {
        swap(&nums[depth], &nums[i]);
        permute(nums, len, depth + 1, callback);
        swap(&nums[depth], &nums[i]);
    }
}

void print_array(const int *arr, size_t len)
{
    for (size_t i = 0; i < len; i++) 
    { 
      printf("%d ", arr[i]); }
      printf("\n"); 
  }
}

int main()
{
  int nums[] = {1, 2, 3};
 permute(nums, sizeof(nums) / sizeof(int), 0, print_array); 
 return 0;
}

        在上面的代码中,我们定义了一个函数 `permute`,用于计算给定数组的排列。在 `permute` 函数中,我们使用递归来生成所有可能的排列,并使用函数指针 `callback` 来指定每当我们生成一个排列时应该调用的函数。在本例中,我们将 `print_array` 函数作为回调函数传递给了 `permute` 函数。这意味着每当 `permute` 函数生成一个排列时,它都会调用 `print_array` 函数来打印这个排列。

在 `main` 函数中,我们定义了一个包含三个整数的数组 `nums`,并使用 `permute` 函数来计算这个数组的所有排列。在每次生成一个排列时,`permute` 函数都会调用 `print_array` 函数来打印这个排列。

  • 函数指针与多态

        多态是面向对象编程中的一个重要概念,它允许我们在不知道对象类型的情况下调用相应的函数。虽然 C 语言不是面向对象编程语言,但我们仍然可以使用函数指针来实现多态。

以下是一个使用函数指针实现多态的示例:

#include <stdio.h>
#include <stdlib.h>

typedef struct shape {
    void (*draw)(struct shape *);
} shape_t;

typedef struct circle {
    shape_t shape;
    int x;
    int y;
    int r;
} circle_t;

typedef struct rectangle {
    shape_t shape;
    int x;
    int y;
    int w;
    int h;
} rectangle_t;

void circle_draw(shape_t *shape) {
    circle_t *circle = (circle_t *)shape;
    printf("Drawing a circle at (%d, %d) with radius %d.\n", circle->x, circle->y, circle->r);
}

void rectangle_draw(shape_t *shape) {
    rectangle_t *rectangle = (rectangle_t *)shape;
    printf("Drawing a rectangle at (%d, %d) with width %d and height %d.\n", rectangle->x, rectangle->y, rectangle->w, rectangle->h);
}

int main() {
    circle_t circle = {
        .shape = {circle_draw},
        .x = 10,
        .y = 20,
        .r = 5,
    };
    rectangle_t rectangle = {
        .shape = {rectangle_draw},
        .x = 30,
        .y = 40,
        .w = 15,
        .h = 20,
    };
    shape_t *shapes[] = {(shape_t *)&circle, (shape_t *)&rectangle};
    for (size_t i = 0; i < sizeof(shapes) / sizeof(shape_t *); i++) {
        shapes[i]->draw(shapes[i]); 
     }
         return 0;
  }

        在上面的代码中,我们定义了一个 `shape` 结构体,它有一个函数指针 `draw`,用于绘制该形状。我们还定义了两个形状:`circle` 和 `rectangle`,它们分别包含它们自己的属性和一个指向 `shape` 结构体的指针。每个形状都定义了自己的 `draw` 函数,用于绘制该形状。

在 `main` 函数中,我们定义了一个 `shape_t` 类型的数组,其中包含一个 `circle` 和一个 `rectangle`。我们使用一个循环来遍历这个数组,并使用每个形状的 `draw` 函数来绘制该形状。注意,尽管 `shapes` 数组中的元素类型为 `shape_t *`,但我们仍然可以调用每个元素的 `draw` 函数,因为 `circle` 和 `rectangle` 都是从 `shape_t` 派生出来的,它们都包含一个 `draw` 函数指针。

这个例子演示了如何使用函数指针来实现多态。尽管 C 语言不支持面向对象编程,但我们可以使用结构体和函数指针来实现类似的概念。

总结

        函数指针是一种强大的工具,可以用于实现许多不同的编程模式和算法。在本文中,我们介绍了函数指针的基本概念和语法,并提供了一些高级应用场景的代码示例,包括回调函数、函数指针数组、函数指针作为参数、函数指针与递归、函数指针与多态等。使用函数指针可以帮助我们编写更加灵活和通用的代码,并提高代码的可重用性和可扩展性。

  • 17
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ch_champion

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值