Page 1 of 1

How to use qsort function in C++? Please help!

Posted: Fri Feb 25, 2005 8:59 am
by frankhuhu
I want to use qsort function.But it says compile error on my VC++6.0
Here is my sample code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int sort_function( const void *a, const void *b);

char list[5][4] = { "cat", "car", "cab", "cap", "can" };


int main(void)
{
int x;

qsort((void *)list, 5, sizeof(list[0]), sort_function);
for (x = 0; x < 5; x++)
printf("%s\n", list[x]);
return 0;
}

int sort_function( const void *a, const void *b)
{
return( strcmp(a,b) );
}

But the compiler says:

error C2664: 'strcmp' : cannot convert parameter 1 from 'const void *' to 'const char *'
Conversion from 'void*' to pointer to non-'void' requires an explicit cast

So is there anyone who can help me to fix the mistake?Thanks!

Posted: Fri Feb 25, 2005 9:47 am
by misof
Next time try actually reading the compiler error message. :P

C++ compilers do a more strict type checking than C. For the C++ compiler, (const void *) and (const char *) are two different things. The error message tells you that if you really want to use the first one as the second one, you have to do an explicit typecast. The following should work:

Code: Select all

int sort_function( const void *a, const void *b) {
  char *aa = (char *) a;
  char *bb = (char *) b;
  return strcmp(aa,bb);
} 
or even

Code: Select all

int sort_function( const void *a, const void *b) {
  return strcmp((char *)a,(char *)b);
} 

Posted: Sat Feb 26, 2005 8:01 am
by frankhuhu
I see!Thanks misof :lol: