I am trying to sort an array of strings using stdlib qsort. Could anyone point to me the step I am missing.
int compare(const void* a, const void* b)
{
const char *ia = (const char *)a;
const char *ib = (const char *)b;
return strcmp(ia, ib);
}
//utility to print strings
void print_strs(char name[][10],int len){
int i=0;
len = 5;
for(i=0;i<len;i++){
printf("%s \n",name[i]);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
char names[5][10] = {"norma","daniel","carla","bob","adelle"};
int size1 = sizeof(names[0]);
int s2 = sizeof(names)/size1;
print_strs(names,5);
qsort(names,s2,sizeof(char),compare);
printf("\n==================\n");
print_strs(names,5);
return 0;
}
Following are the issues in the output :
1.unsorted strings 2.first string of the array is incorrect(Norma printed as amnor).
norma
daniel
carla
bob
adelle
==================
amnor
daniel
carla
bob
adelle
char *s (as your comparison function is defined) or an array ofchar[10]s (as the array is declared) or an array ofchars (according to the size you passed to qsort).sizeof(char)-->size1