使用 qsort() 使用函数指针按用户希望的顺序排序的 C 代码

C code for using qsort() to sort in the order the user wants using function pointers

我正在创建一个 C 代码以使用 qsort() 进行排序。我需要从用户那里得到一个数组,然后我需要从用户那里得到一个以升序打印这个数组,如果我想按降序打印它则需要 d。问题是我需要使用函数指针来做到这一点。我尝试使用函数指针数组,但问题是用户需要输入两个字符。

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


int  a( const void *va , const void * vb )
 {
    const int * a = ( const int *) va ;
    const int * b = ( const int *) vb ;
    if (* a < *b ) return -1;
    else if (* a > * b) return 1;
    else return 0;
 }

 int  d( const void *va , const void * vb )
 {
    const int * a = ( const int *) va ;
    const int * b = ( const int *) vb ;
    if (* a < *b ) return 1;
    else if (* a > * b) return -1;
    else return 0;
 }


int main()
{
    int *arr;
    int n, i;
    char c;

    scanf("%d", &n);

    arr=(int*)malloc(sizeof(int)*n);

    for(i=0;i<n;i++)
    {
        scanf("%d", &arr[i]);
    }

    while(1)
    {
        scanf("%c", &c);
        getchar();
        if(c=='e')
            break;


        qsort ( arr , n , sizeof(arr[0]) , d);
    }

    for(i=0;i<n;i++)
    {
    printf("%d", arr[i]);
    }
    return 0;
}

因此,声明一个 pointer-to-function 变量 comparison_func,并在 if 语句中设置它:

int (*comparison_func)(const void *, const void *);

if (c == 'a') {
    comparison_func = a;
}
else if (c == 'c') {
    comparison_func = d;
}

然后在调用 qsort:

时使用这个 comparison_func
qsort(arr, n, sizeof(arr[0]), comparison_func);

或者您可以声明一个具有选项字符和相应指针的struct

typedef struct sortfunc {
    char option;
    int (*comparison_func)(const void *, const void *);
} SORTFUNC;

SORTFUNC sort_funcs[] = {
    {'a', a},
    {'d', d},
    {0,   0}
};

然后通过这个数组找到匹配的选项字符:

SORTFUNC *i;
for (i = sort_funcs; i->option && i->option != c; i++);
if (! i->comparison_func) {
    printf("choice %c is invalid\n", c);
}
else {
    qsort(..., i->comparison_func);
}