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]

2
  • 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 *). Commented Feb 21, 2013 at 0: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<b Commented Feb 21, 2013 at 0:51

3 Answers 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_; ... } 
Sign up to request clarification or add additional context in comments.

1 Comment

Huh, that's quite a complicated concept if you are not familiar to it. void is "nothing", the "unknown" type. Read 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.
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 } 

Comments

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; /* ... */ } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.