Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass a variable to a function here?

Tags:

c

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!

like image 608
Tim Avatar asked Apr 10 '14 17:04

Tim


People also ask

How do you pass a variable address to a function?

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)++; .


1 Answers

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.

like image 141
Mahonri Moriancumer Avatar answered Sep 20 '22 10:09

Mahonri Moriancumer