How to pass a variable to a function here?

I am using qsort from stdlib.h,

void qsort (void* base, size_t num, size_t size, int (*compar)(const void*,const void*)); 

in the following way:

 void myfun (float *arr, int n, float c) // value of c is changeable { ...// some code qsort(float *arr, n, sizeof(float), compareme); ...// some code } 

with

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

how can i make c usable in compareme here?

Thanks!

+6
source share
2 answers

Many resort to using a (nasty) global variable.

Too bad qsort () does not contain an extra void pointer argument, which is simply passed to the user-provided compare () function. I ended up writing my own qsort () to overcome this limitation.

Prototype:

 int myQsort( void *arrayBase, size_t elements, size_t elementSize, int(*compar)(const void *, const void *, void *callerArg), void *callerArg ); 

This allows me to pass all kinds of structures (cast in void *) to my compar () fn.

+4
source

If you use Glibc (i.e. Linux), you can use qsort_r :

 int compareme (const void *a, const void *b, void *data) { float c = *(float *)data; float tmp = f((float*)a, (float*)b, c); if (tmp < 0) return -1; if (tmp == 0) return 0; if (tmp > 0) return 1; } 

then call

 qsort_r(float *arr, n, sizeof(float), compareme, &c); 

You must define the _GNU_SOURCE preprocessor macro before including any headers to get this (for example, using -D_GNU_SOURCE ) to get this function, and this will limit your portability of the program.

Otherwise, you will have to use global or streaming storage or write your own sort function.

+4
source

All Articles