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
int mainAnd explicit casts fromvoid*to some other data-pointer-type are not needed and should not be done in C. Also, avoid passing a type tosizeofinstead of an expression, that's error-prone.