2

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]

4

3 回答 3

2

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_;
    ...
}
于 2013-02-21T00:51:41.793 回答
1

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
}
于 2013-02-21T00:51:54.413 回答
1

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;

   /* ... */
}
于 2013-02-21T00:52:05.317 回答