我正在创建一个 C 代码来使用 qsort() 进行排序。我需要从用户那里获取一个数组,之后我需要从用户那里获取 a 以升序打印该数组,如果我想以降序打印它则需要 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;
}
最佳答案
因此,声明一个函数指针变量 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);
}
关于使用 qsort() 使用函数指针按照用户想要的顺序进行排序的 C 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42313784/