NO

Author Topic: qsort  (Read 2984 times)

czerny

  • Guest
qsort
« on: January 17, 2012, 09:41:32 PM »
Sorry,

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

Code: [Select]
#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

Code: [Select]
Dexter | Forest | Bill | Celine | Alex | Zorro |
czerny

CLR

  • Guest
Re: qsort
« Reply #1 on: January 17, 2012, 11:02:26 PM »
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

  • Guest
Re: qsort
« Reply #2 on: January 18, 2012, 12:43:23 AM »
Thanks!

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

czerny

Offline TimoVJL

  • Global Moderator
  • Member
  • *****
  • Posts: 2115
Re: qsort
« Reply #3 on: January 18, 2012, 08:50:52 AM »
So we need compare function something like this:
Code: [Select]
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]);
}
or
Code: [Select]
int __cdecl cmpfunc(const void *elem1, const void *elem2)
{
//printf("%s %s\n", *(char**)elem1, *(char**)elem2);
return strcmp(*(char**)elem1, *(char**)elem2);
}
« Last Edit: January 18, 2012, 09:00:34 AM by timovjl »
May the source be with you