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);
}
相关推荐
2501_914245931 小时前
C语言设计模式详解:从理论到实践的完整指南
c语言·开发语言·设计模式
2501_914245933 小时前
C语言与硬件交互:从GPIO到中断的嵌入式编程实践
c语言·单片机·交互
炸膛坦客4 小时前
单片机/C/C++八股:(二十四)编译文件( .bin 和 .hex ,包括 .elf 和 .axf )
c语言·c++·单片机
简单电磁炮7 小时前
硬件基础4
c语言
炸膛坦客9 小时前
单片机/C/C++八股:(二十三)#define 和 typedef 的区别
c语言·c++·单片机
捷瑞电子工坊11 小时前
C语言取地址符 `&` 极简教程
c语言·c语言基础·取地址符·指针入门
乱七八糟的屋子12 小时前
LibYAML超全教程-C语言YAML解析与生成
c语言·开发语言·配置文件·yaml解析·libyaml·开源库实战
小肝一下12 小时前
2. 顺序表和链表
c语言·数据结构·c++·链表·dijkstra·依蕾娜·香香的依蕾娜
j7~12 小时前
【数据结构初阶】带头双向循环链表 (DSList) --增删查改完整实现详解
c语言·数据结构·链表·带头双向循环链表
无相求码1 天前
【C语言】字符串的本质是什么,为什么 strlen 会读到野内存
c语言·开发语言