Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warning when using qsort in C

Tags:

c

qsort

I wrote my comparison function

int cmp(const int * a,const int * b)
 {
   if (*a==*b)
   return 0;
else
  if (*a < *b)
    return -1;
else
    return 1;
}

and i have my declaration

int cmp (const int * value1,const int * value2);

and I'm calling qsort in my program like so

qsort(currentCases,round,sizeof(int),cmp);

when i compile it I get the following warning

warning: passing argument 4 of ‘qsort’ from incompatible pointer type
/usr/include/stdlib.h:710: note: expected ‘__compar_fn_t’ but argument is of type ‘int
(*)(const int *, const int *)’

The program works just fine so my only concern is why it doesn't like the way im using that?

like image 604
Matt Phillips Avatar asked Apr 01 '10 15:04

Matt Phillips


1 Answers

The cmp function's prototype must be

int cmp(const void* a, const void* b);

You can either cast it in the invocation of qsort (not recommended):

qsort(currentCases, round, sizeof(int), (int(*)(const void*,const void*))cmp);

or casts the void-pointers to int-pointers in cmp (the standard approach):

int cmp(const void* pa, const void* pb) {
   int a = *(const int*)pa;
   int b = *(const int*)pb;
   ...
like image 107
kennytm Avatar answered Sep 28 '22 00:09

kennytm