Warning when using qsort in C

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 ad

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

and I call qsort in my program like this

 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 problem is why she doesn't like how she uses it?

+4
source share
2 answers

The prototype of the cmp function should be

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

You can specify it in a qsort call (not recommended):

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

or discards void pointers to int pointers in cmp (standard approach):

 int cmp(const void* pa, const void* pb) { int a = *(const int*)pa; int b = *(const int*)pb; ... 
+19
source

According to the man page, __compar_fn_t is defined as: typedef int(*) __compar_fn_t (const void *, const void *)

Your cmp specifies int* parameters. I don’t like it, but it only displays as a warning.

0
source

Source: https://habr.com/ru/post/1305778/


All Articles