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]

kay
  • 24,516
  • 10
  • 94
  • 138
jack stov
  • 63
  • 1
  • 1
  • 6
  • 2
    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 Feb 21 '13 at 00:49
  • 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 – jack stov Feb 21 '13 at 00:51

3 Answers3

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_;
    ...
}
kay
  • 24,516
  • 10
  • 94
  • 138
  • Huh, that's quite a complicated concept if you are not familiar to it. `void` is "nothing", the "unknown" type. Read http://stackoverflow.com/q/1043034/ for a better explanations. In C++ (or Java ...) you would use templates instead of an undefined type, but C does not have such a concept. – kay Feb 21 '13 at 00:57
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
}
Fred Foo
  • 342,876
  • 71
  • 713
  • 819
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;

   /* ... */
}
perreal
  • 90,214
  • 20
  • 145
  • 172