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);
}
相关推荐
C羊驼4 分钟前
C语言学习笔记(十):操作符
c语言·开发语言·经验分享·笔记·学习
自信150413057591 小时前
选择排序算法
c语言·数据结构·算法·排序算法
hongtianzai1 小时前
Laravel7.x十大核心特性解析
java·c语言·开发语言·golang·php
weixin_649555671 小时前
C语言程序设计第四版(何钦铭、颜晖)第十章函数与程序结构之统计完全平方数
c语言·数据结构·算法
_饭团2 小时前
C 语言数据存储全解析:原反补码、大小端与 IEEE 754 浮点数
c语言·数据结构·算法·leetcode·面试·蓝桥杯·学习方法
m0_488633322 小时前
C语言学习笔记:探索简洁灵活且具多种特性的编程语言
c语言·学习笔记·编程语言·简洁性·灵活性
Felven3 小时前
C. Stable Groups
c语言·开发语言
C羊驼3 小时前
C语言学习笔记(十二):动态内存管理
c语言·开发语言·经验分享·笔记·青少年编程
hongtianzai3 小时前
Laravel8.x核心特性全解析
java·c语言·开发语言·golang·php
山上三树3 小时前
C/C++ 中,整数 ↔ 字符、整数 ↔ 字符串
c语言·c++