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!
How to use qsort function in C++? Please help!
Moderator: Board moderators
Next time try actually reading the compiler error message. ![:P](./images/smilies/icon_razz.gif)
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:
or even
![:P](./images/smilies/icon_razz.gif)
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);
}
Code: Select all
int sort_function( const void *a, const void *b) {
return strcmp((char *)a,(char *)b);
}