我使用stdlib.h中的qsort,
void qsort (void* base, size_t num, size_t size,
int (*compar)(const void*,const void*));
Run Code Online (Sandbox Code Playgroud)
以下列方式:
void myfun (float *arr, int n, float c) // value of c is changeable
{
...// some code
qsort(float *arr, n, sizeof(float), compareme);
...// some code
}
Run Code Online (Sandbox Code Playgroud)
同
int compareme (const void * a, const void * b)
{
float tmp = f((float*)a, (float*)b, c ); // f is some function, and how can I pass c here?
if (tmp < 0) return -1;
if (tmp == 0) return 0;
if (tmp > 0) return 1;
}
Run Code Online (Sandbox Code Playgroud)
我怎么能c在compareme这里使用?
谢谢!
小智 4
许多人求助于使用(讨厌的)全局变量。
遗憾的是 qsort() 不包含一个额外的 void 指针参数,该参数只是传递给用户提供的 compar() 函数。我最终编写了自己的 qsort() 来克服这个限制。
原型:
int myQsort(
void *arrayBase,
size_t elements,
size_t elementSize,
int(*compar)(const void *, const void *, void *callerArg),
void *callerArg
);
Run Code Online (Sandbox Code Playgroud)
这允许我将各种结构(强制转换为 void *)传递给我的 compar() fn。