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

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
frankhuhu
New poster
Posts: 30
Joined: Tue Jul 20, 2004 5:22 am
Contact:

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

Post 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!
misof
A great helper
Posts: 430
Joined: Wed Jun 09, 2004 1:31 pm

Post 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);
} 
frankhuhu
New poster
Posts: 30
Joined: Tue Jul 20, 2004 5:22 am
Contact:

Post by frankhuhu »

I see!Thanks misof :lol:
Post Reply

Return to “C++”