According to this site, I have done the following program which sorts strings.
#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char list[5][4]={"dat","mai","lik","mar","ana"};
int main(int argc, char *argv[])
{
int x;
puts("sortirebamde:");
for (x=0;x>sizeof(list)/sizeof(char);x++)
printf("%s\n",list[x]);
qsort(&list,(sizeof(list)/sizeof(char)),sizeof(list[0]),strcmp);
system("PAUSE");
return EXIT_SUCCESS;
}
Here is the error I get
13 C:\Documents and Settings\LIBRARY\Desktop\string_sortireba.cpp invalid conversion from `int (*)(const char*, const char*)' to `int (*)(const void*, const void*)'
13 C:\Documents and Settings\LIBRARY\Desktop\string_sortireba.cpp initializing argument 4 of `void qsort(void*, size_t, size_t, int (*)(const void*, const void*))'
Please help
Please note: It is unusual to store C strings in two dimensional char arrays. It’s more normal to have
char *ary[], such as argv. That type cannot be sorted directly usingqsortandstrcmp, because qsort will passchar **notchar *to the comparison function. This is good for efficiency, the pointers can be swapped instead of the whole strings. The Linux manpage for qsort has some good example code with a correct comparison function.You can’t pass
strcmpdirectly toqsortas its comparison function becauseqsortexpects to pass pointers tovoidwherestrcmpexpects pointers toconst char. Given the required similarity between pointers tovoidand pointers tochar, you could probably do it with a cast (for your code), but the cleaner way would be to write a function that takes the right types:Note, however, that in C++ you’d normally want to use
std::sortinstead ofqsort, and probably usestd::stringinstead ofchar *, which case the sorting gets a lot simpler (and generally faster as well).