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);
}
相关推荐
序属秋秋秋7 小时前
《Linux系统编程之进程环境》【地址空间】
linux·运维·服务器·c语言·c++·系统编程·进程地址空间
Tandy12356_7 小时前
中科大计算机网络——网络安全
c语言·python·计算机网络·安全·web安全
枫叶丹48 小时前
【Qt开发】Qt窗口(五) -> 非模态/模态对话框
c语言·开发语言·数据库·c++·qt
zore_c18 小时前
【C语言】带你层层深入指针——指针详解2
c语言·开发语言·c++·经验分享·笔记
奔跑吧邓邓子20 小时前
【C语言实战(72)】C语言文件系统实战:解锁目录与磁盘IO的奥秘
c语言·文件系统·目录·开发实战·磁盘io
The Last.H21 小时前
Educational Codeforces Round 185 (Rated for Div. 2)A-C
c语言·c++·算法
松涛和鸣1 天前
DAY20 Optimizing VS Code for C/C++ Development on Ubuntu
linux·c语言·开发语言·c++·嵌入式硬件·ubuntu
unclecss1 天前
从 0 到 1 手写 Linux 调试器:ptrace 系统调用与断点原理
linux·运维·服务器·c语言·ptrace
fashion 道格1 天前
从地图导航到数据结构:解锁带权有向图的邻接链表奥秘
c语言·数据结构·链表
猿大叔~1 天前
面试必问!Linux 下 C/C++ 内存对齐深度解析:从底层原理到实战避坑
linux·c语言·面试