Reputation: 1843
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
Upvotes: 2
Views: 2109
Reputation: 2720
You are passing wrong size
while calling qsort
. You are passing sizeof(char)
as the size of your individual element, which is wrong. In your case each individual element is a string with ten characters.
So, you can correct that by either calling qsort
as:
qsort(names,s2,sizeof(char) * 10,compare);
Or, as you already have captured this value in size1
, you can use that, as:
qsort(names,s2,size1,compare);
Upvotes: 1