2

I tried to sort an array of string using qsort. here is the content of my array:

{"a","orange","apple","mobile","car"}

this is how I use qsort:

int myCompare (const void * a, const void * b ) {
  const char *pa = (const char*)a;
  const char *pb = (const char*)b;
  return strcmp(pa,pb);
}

int stringLen = sizeof(input)/sizeof(char *);
qsort(input, stringLen, sizeof (char*), myCompare);

However, when I print the array, nothing is changed. is there something wrong w/ this?

jack stov
  • 63
  • 1
  • 1
  • 6

3 Answers3

10

I've changed your myCompare function to what Mitch Wheat had posted earlier, and that works properly. Here's the example:

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

int myCompare (const void * a, const void * b ) {
    const char *pa = *(const char**)a;
    const char *pb = *(const char**)b;

    return strcmp(pa,pb);
}

int main() {
    int i;
    const char *input[] = {"a","orange","apple","mobile","car"};

    int stringLen = sizeof(input) / sizeof(char *);
    qsort(input, stringLen, sizeof(char *), myCompare);

    for (i=0; i<stringLen; ++i)
        printf("%d: %s\n", i, input[i]);
}

This will return:

0: a
1: apple
2: car
3: mobile
4: orange
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
4

qsort(input, stringLen, sizeof (char*), myCompare) calls myCompare to compare strings which are sorted.

myCompare gets pointers to compared values. In our case we get pointers to strings (const char**). So we should compare *(const char**)a and *(const char**)b, which are strings pointed by a and b.

wkordalski
  • 938
  • 8
  • 9
2

Start debugging with:

int myCompare (const void * a, const void * b ) {
  const char *pa = (const char*)a;
  const char *pb = (const char*)b;

  printf("Comparing %s vs. %s for result %d\n", pa, pb, strcmp(pa,pb));

  return strcmp(pa,pb);
}

I think shortly after that, you'll figure out the problem. :)

abelenky
  • 63,815
  • 23
  • 109
  • 159