News:

Download Pelles C here: http://www.smorgasbordet.com/pellesc/

Main Menu

qsort

Started by czerny, January 17, 2012, 09:41:32 PM

Previous topic - Next topic

czerny

Sorry,

I must do something silly here. But I do not find my error:

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

int main(int argc, char **argv)
{
char *strings[] = { "Zorro", "Alex", "Celine", "Bill", "Forest", "Dexter" };
    size_t i, num = sizeof(strings) / sizeof(char *);

qsort(strings, num, sizeof(char *), strcmp);

for(i=0; i<num; i++) printf("%s | ", strings[i]); putchar('\n');

return 0;
}


returns

Dexter | Forest | Bill | Celine | Alex | Zorro |

czerny

CLR

This is because your comparator function expects a pointer to the first and to the second element, each element is already a pointer, so you receive a pointer to a pointer.

czerny

Thanks!

That's what I thought. It was something silly!

czerny

TimoVJL

#3
So we need compare function something like this:int __cdecl cmpfunc(const void *elem1, const void *elem2)
{
//printf("%s %s\n", ((char**)elem1)[0], ((char**)elem2)[0]);
return strcmp(((char**)elem1)[0], ((char**)elem2)[0]);
}
orint __cdecl cmpfunc(const void *elem1, const void *elem2)
{
//printf("%s %s\n", *(char**)elem1, *(char**)elem2);
return strcmp(*(char**)elem1, *(char**)elem2);
}
May the source be with you