Can you use qsort to sort an array strings?

I would like to sort an array of strings. Here is part of the code that I tried but I keep getting this error message:

"warning C4133: 'function' : incompatible types - from 'char (__cdecl *)(const void *,const void *)' to 'int (__cdecl *)(const void *,const void *)'"


Can anyone see my error?


#include

#include

char asc (const void *, const void *);


void main()

{

char pcodes[50][7];

qsort(pcodes, 50, sizeof(char), asc);

(I only posted the part if the code that involved

qsort)


/********ASC*********/


char asc(const void *a, const void*b)

{

if(*(char*)a < *(char*)b) return -1;

if(*(char*)a > *(char*)b) return 1;

return 0;

}


Comments

  • : I would like to sort an array of strings. Here is part of the code that I tried but I keep getting this error message:

    : "warning C4133: 'function' : incompatible types - from 'char (__cdecl *)(const void *,const void *)' to 'int (__cdecl *)(const void *,const void *)'"


    : Can anyone see my error?


    : #include

    : #include

    : char asc (const void *, const void *);


    |||| why not use int here instead of char ?




    : void main()

    : {

    : char pcodes[50][7];

    : qsort(pcodes, 50, sizeof(char), asc);

    : (I only posted the part if the code that involved

    : qsort)


    : /********ASC*********/


    : char asc(const void *a, const void*b)


    |||| and here too


    : {

    : if(*(char*)a < *(char*)b) return -1;

    : if(*(char*)a > *(char*)b) return 1;

    : return 0;

    : }







  • To sort array use strcmpi-commands


  • Strings cannot be compared directly in C/C++. You must use a string compare routine. strcmp is one of them (check out string.h).


    Additionally, your compiler is complaining about a type-mismatch. You're passing around function pointers. qsort expects a comparison routine that takes two constant void pointers to data and returns an int describing the ordering. If your comparison routine doesn't have this exact property, then passing it in as a function pointer won't work. Your compiler will complain that you gave it a pointer to a function that doesn't match what it was expecting.






Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories