0

I'm trying to sort a string array in alphabetized order using qsort.

When I use comp1, which casts the arguments to char**, it works well.
But not if I use comp2, which casts to char* instead.

Why? I can't understand the difference between comp1 and comp2.

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

int comp1(const void *a, const void *b) {
    const char **pa = (const char **)a;
    const char **pb = (const char **)b;
    return strcmp(*pa, *pb);
}
int comp2(const void *a, const void *b) {
    const char *pa = (const char *)a;
    const char *pb = (const char *)b;
    return strcmp(pa, pb);
}
void main(void) {
    char *array[] = {"c","b","a"};
    int size = sizeof(array)/sizeof(char *);
    int i;
    qsort(array,size,sizeof(char *),compX);
    //compX is comp1 or comp2
    for(i=0;i<size;i++){
        printf("%s",array[i]);
    }
}

outputs

abc ← when I use comp1

cba ← when I use comp2

1
  • As an aside, it's int main And explicit casts from void* to some other data-pointer-type are not needed and should not be done in C. Also, avoid passing a type to sizeof instead of an expression, that's error-prone. Commented Jan 24, 2015 at 11:16

1 Answer 1

1

Your array is an array of pointers to strings.
As the comparator-function always gets pointers to the starts of the elements sorted, that means it gets void* which point to char* to those strings.

Casting those void* to char* is obviously one indirection too few.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh,I've understood!char*'s pointer is char**.Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.