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);
}
相关推荐
独小乐1 小时前
019.ADC转换和子中断|千篇笔记实现嵌入式全栈/裸机篇
linux·c语言·驱动开发·笔记·嵌入式硬件·mcu·arm
Rabitebla4 小时前
C++ 和 C 语言实现 Stack 对比
c语言·数据结构·c++·算法·排序算法
深邃-4 小时前
【数据结构与算法】-顺序表链表经典算法
java·c语言·数据结构·c++·算法·链表·html5
charlie1145141917 小时前
嵌入式Linux驱动开发指南02——内核空间基础与硬件访问
linux·运维·c语言·驱动开发·嵌入式硬件
少司府7 小时前
C++基础入门:内存管理
c语言·开发语言·c++·内存管理·delete·new·malloc
鱼很腾apoc7 小时前
【学习篇】第17期 C++入门必看——类和对象全站最详篇
c语言·开发语言·学习·算法·青少年编程
Sakuyu434687 小时前
C语言基础(一)
c语言·开发语言
码农的神经元7 小时前
2026 MathorCup C 题实战复盘:从高血脂风险预警到 6 个月干预优化的建模思路与 Python 落地
c语言·开发语言·python
良木生香8 小时前
【C++初阶】C++编程基石:编码表&&STL的入门指南
c语言·开发语言·数据结构·c++·算法
达帮主8 小时前
19.1 C语言链表 -- 简单
c语言·开发语言·链表