I use 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!
Example 2: Passing Pointers to Functions Here, the value stored at p , *p , is 10 initially. We then passed the pointer p to the addOne() function. The ptr pointer gets this address in the addOne() function. Inside the function, we increased the value stored at ptr by 1 using (*ptr)++; .
Many resort to using a (nasty) global variable.
It is too bad that qsort() doesn't include an extra void pointer argument that is just passed to the user-supplied compar() 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 to void *) to my compar() fn.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With