-5

Why when we use qsort(), int(*compar)(const void*,const void*) haven't add any paraments in, but can also do their functions?

Such as this :

double vals[NUM];
qsort(vals,NUM,sizeof(double),mycomp);
Dhanuka
  • 2,826
  • 5
  • 27
  • 38
xptrickt
  • 1
  • 2

3 Answers3

1

When you append parenthesis to the identifier representing a function, with a list of parameters between, you're calling the function.

In this case, you don't want to call the function, however. You want qsort to call the function to determine whether or not one element is larger or smaller than the other.

autistic
  • 1
  • 3
  • 35
  • 80
  • Mmmmmm,does this mean when I use qsort ,I don't have to concern about how mycomp work? – xptrickt May 30 '15 at 06:53
  • It means you should write `mycomp` to compare the two items that are pointed to by the two arguments. – autistic May 30 '15 at 06:57
  • `int mycomp(const void *x, const void *y) { const double *a = x, *b = y; /* return -1 when a is less than b, 0 when they're equal or 1 when a is greater than b */ }` – autistic May 30 '15 at 07:12
0

It seems you are asking about function pointers in general.

Here is a simple example of function pointer:

int compare(int i, int j)
{
    return i > j ? i : j;
}

void process(int i, int j, int(*pfunc)(int, int))
{
    printf("%d\n", pfunc(i, j));
}

int main(void)
{
    process(1, 2, compare);
    return 0;
}

In this example process is sort of like qsort, while compare is the function which we define ourselves. We need to tell qsort how to compare data, but we can't access qsort directly, so pass our own function to it which tells qsort how to compare.

Community
  • 1
  • 1
Barmak Shemirani
  • 30,904
  • 6
  • 40
  • 77
  • I agree most of what you said,but one point I can't understand is that when we use qsort,we define mycomp,but we even don't know how the mycomp proceed data segmentation? – xptrickt May 30 '15 at 15:30
0

qsort is generic. It doesn't know what type of data it is processing, so it can't simply compare elements using <. What it does instead is let you, the programmer, give it a function to use to compare elements. So, yes you do care about how mycomp works, you need to define it.

int mycomp(const void *a, const void *b) {
    const double *lhs = a;
    const double *rhs = b;
    if (*lhs < *rhs) return -1;
    if (*lhs > *rhs) return 1;
    return 0;
}

inside of qsort, every time it needs to compare two elements it will pass them to your mycomp function and examine the result. If you define it wrong, your array will be incorrectly arranged (unsorted).

Ryan Haining
  • 35,360
  • 15
  • 114
  • 174