2
votes

So, I have an array of string (name input), and I want to sort that array. I use something like this

int stringLen = sizeof(input)/sizeof(char *);
qsort(input, stringLen, sizeof(char *), myCompare);

However I get this confusing error:

error: invalid conversion from 'int (*)(const char*, const char*)' to '__compar_fn_t {aka int (*)(const void*, const void*)}' [-fpermissive]

In file included from srot13u.c:5:0: /usr/include/stdlib.h:761:13: error: initializing argument 4 of 'void qsort(void*, size_t, size_t, __compar_fn_t)' [-fpermissive]

3
What is myCompare? Is it int myCompare(const char *, const char *)? Because the error message suggests it expects myCompare to look like int myCompare(const void *, const void *).ta.speot.is
a compare method that I write. int myCompare(char const *a,char const *b). it will return 1 if a>b, 0 if a=b, -1 if a<bjack stov

3 Answers

2
votes

Your myCompare function has the signature:

int myCompare(const char*, const char*)

but

int myCompare(const void*, const void*)

is expected.

Just use

int myCompare(const void *a_, const void *b_) {
    const char *a = a_;
    const char *b = b_;
    ...
}
1
votes

You're passing an function taking two char pointers, but qsort wants one that takes void pointers. These two function pointer types are not compatible in C.

Change your comparison routine; the common setup is something like

static int strcmp_void(const void *a, const void *b)
{
    return strcmp(a, b);  // the types *are* compatible in this expression
}
1
votes

Change your myCompare like this:

int myCompare(const void* pa, const void* pb) {
   const char *a = (const char*)pa;
   const char *b = (const char*)pb;

   /* ... */
}