函数指针(pointer to function)——qsort函数应用实例

一,举例应用

  在ACM比赛中常使用 stdlib.h 中自带的 qsort 函数,是教科书式的函数指针应用示范。

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

int comp(const void*a, const void*b)
{
    return *(int*)a - *(int*)b;
}

int main()
{
    int n = 5;
    int *array = (int*)malloc(n*sizeof(int)); 
    int i = 0;
    for (; i<n; i++)
    {
        *(array + i) = 10 - i;
    }
    qsort(array, n, sizeof(int), comp);
    for (i = 0; i<n; i++)
    {
        printf("%d	", array[i]);
    }
    return 0;
}

 二,总结

  函数指针变量通常的用途之一,是把指针作为参数传递到其他函数。

  调用函数指针的例子:

int locateElem(LinearList *pL, ElemType e, int (*compare)(ElemType*, ElemType*))

  其中 compare 是函数指针名,(ElemType*, ElemType*)是函数指针的参数。

  调用函数指针的例子:

if ((*compare)(&e1, &e2) == 0)
    return i;

  参数 &e1 和 &e2 是两个类型为 ElemType* 的变量。

原文地址:https://www.cnblogs.com/fengyubo/p/4863690.html