C 函数指针

就像指针可以指向一般变量、数组、结构体那样,指针也可以指向函数。

函数指针的主要用途是向其他函数传递"回调",或者模拟类和对象。

形式如下:

cpp 复制代码
int (*POINTER_NAME)(int a, int b)

这类似于指向数组的指针可以表示所指向的数组。指向函数的指针也可以用作表示所指向的函数,只不过是不同的名字。

cpp 复制代码
int (*tester)(int a, int b) = sorted_order;
printf("TEST: %d is same as %d\n", tester(2, 3), sorted_order(2, 3));

使用**typedef** 可以给其它更复杂的类型起个新的名字。你需要记住的事情是,将**typedef**添加到相同的指针语法之前,然后你就可以将那个名字用作类型了。

cpp 复制代码
#include <stdio.h>
#include <stdlib.h>


typedef int (*compare_cb)(int a, int b);

/**
 * A classic bubble sort function that uses the
 * compare_cb to do the sorting.
 */

int *bubble_sort(int *numbers, int count, compare_cb cmp)
{
    int temp = 0;
    int i = 0;
    int j = 0;
    int *target = malloc(count * sizeof(int));

    memcpy(target, numbers, count * sizeof(int));

    for(i = 0; i < count; i++) {
        for(j = 0; j < count - 1; j++) {
            if(cmp(target[j], target[j+1]) > 0) {
                temp = target[j+1];
                target[j+1] = target[j];
                target[j] = temp;
            }
        }
    }

    return target;
}

int sorted_order(int a, int b)
{
    return a - b;
}

int reverse_order(int a, int b)
{
    return b - a;
}


void test_sorting(int *numbers, int count, compare_cb cmp)
{
    int i = 0;
    int *sorted = bubble_sort(numbers, count, cmp);
    for(i = 0; i < count; i++) {
        printf("%d ", sorted[i]);
    }
    printf("\n");

    free(sorted);
}
相关推荐
小鱼23338 分钟前
STM32中的中断机制与应用
c语言·stm32·单片机·嵌入式硬件·mcu
阿华hhh34 分钟前
单片机day1
c语言·单片机·嵌入式硬件
我还可以再学点35 分钟前
C语言常见函数
c语言·开发语言
黎雁·泠崖1 小时前
吃透Java操作符高阶:位操作符+赋值操作符 全解析(Java&C区别+实战技巧+面试考点)
java·c语言·面试
超级无敌大学霸1 小时前
c语言整型提升
c语言·开发语言
kklovecode3 小时前
C语言数组:零长数组,可变数组,多维数组
java·c语言·算法
南棱笑笑生4 小时前
20260113给飞凌OK3588-C开发板适配Rockchip原厂的Android14系统时适配CAM3接口的OV5645
c语言·开发语言·rockchip
%xiao Q4 小时前
信息学奥赛一本通(部分题解)
c语言·c++·算法
枫叶丹44 小时前
【Qt开发】Qt系统(六)-> Qt 线程安全
c语言·开发语言·数据库·c++·qt·安全
你怎么知道我是队长4 小时前
C语言---错误处理
c语言·开发语言