jack stov
jack stov

Reputation: 63

confusing error with qsort method

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]

Upvotes: 2

Views: 2417

Answers (3)

perreal
perreal

Reputation: 98118

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;

   /* ... */
}

Upvotes: 1

Fred Foo
Fred Foo

Reputation: 363817

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
}

Upvotes: 1

Kijewski
Kijewski

Reputation: 26043

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_;
    ...
}

Upvotes: 2

Related Questions