LCTHW - 18

18. 函数指针

C语言中的函数实际上都是指向一段代码的指针(这段代码就是函数的实现).就像创建指向结构体, 变量的指针一样, 你也可以把一个指针指向函数. 函数指针的主要用途在于给其他函数传"回调"(callback), 或者用来模拟类和对象.

函数指针的形式是这样的:

int (*POINTER_NAME)(int a, int b)

和函数的声明看起来很相似, 区别在于:

  • 在函数名字外面包了一层指针的语法
  • 函数的声明是一条语句, 而函数指针是一个变量

当你定义了一个函数指针后, 这个指针变量的使用方法就像它指向的指针一样, 只是换了一个名字.

int (*tester)(int a, int b) = sort_order; //注意 sort_order 不要带括号
printf ("TEST: %d is same as %d\n", tester(2, 3), sort_order(2, 3));

如果 函数指针 指向的 函数 的 返回值 是 指针 的话, 是这个样子的:

首先函数长这样 : char *func(int a) {}
把函数名用指针包上: char *(*func)(int a)
然后改个名字 : char *(*p_func)(int a)

解决了函数指针的基本定义, 来看函数指针的另一个问题: 怎么把一个函数指针以参数的形式传进另一个函数呢? 函数的参数都是有类型的, 那么首先要让函数指针有自己的类型. 我们知道函数是由返回值和参数决定的, 那么函数指针的类型也是如此, 我们用 typedef 来定义一个函数指针的类型:

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

这样, 就可以用 func_type 来作为函数的类型了, 这类型的函数返回值为一个 int, 参数为两个 int.

我们来看下面一段代码
这里主要看 typedef, 定义了一个函数的类型.
然后程序最后的 test_sorting, 传入了三个函数指针.

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

/** Our old friend die from ex17. */
void die(const char *message)
{
    if(errno) {
        perror(message);
    } else {
        printf("ERROR: %s\n", message);
    }

    exit(1);
}

// a typedef creates a fake type, in this
// case for a function pointer
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));

    if(!target) die("Memory error.");

    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;
}

int strange_order(int a, int b)
{
    if(a == 0 || b == 0) {
        return 0;
    } else {
        return a % b;
    }
}

/** 
 * Used to test that we are sorting things correctly
 * by doing the sort and printing it out.
 */
void test_sorting(int *numbers, int count, compare_cb cmp)
{
    int i = 0;
    int *sorted = bubble_sort(numbers, count, cmp);

    if(!sorted) die("Failed to sort as requested.");

    for(i = 0; i < count; i++) {
        printf("%d ", sorted[i]);
    }
    printf("\n");

    free(sorted);
}

int main(int argc, char *argv[])
{
    if(argc < 2) die("USAGE: ex18 4 3 1 5 6");

    int count = argc - 1;
    int i = 0;
    char **inputs = argv + 1;

    int *numbers = malloc(count * sizeof(int));
    if(!numbers) die("Memory error.");

    for(i = 0; i < count; i++) {
        numbers[i] = atoi(inputs[i]);
    }

    test_sorting(numbers, count, sorted_order);
    test_sorting(numbers, count, reverse_order);
    test_sorting(numbers, count, strange_order);

    free(numbers);

    return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容