I'm trying to write a simple string sorting program using qsort().(inspired from program in qsort manual in Linux)
This is my code.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void disparray(int i,char words[10][20]);
int compare_strings(const void *a,const void *b);
int main()
{
int index=0;
char words[10][20];
while(fgets(words[index],20,stdin)) //take array of strings as input from stdin
{
if (words[index][0]=='\n') break;
words[index][ strlen(words[index]) - 1 ] = '\0'; //to remove trailing newline
index++;
if (index==10)break;
}
disparray(index,words);
qsort(words,index,sizeof(char*),compare_strings);
disparray(index,words);
return 0;
}
int compare_strings(const void *a,const void *b)
{
//return strcmp(*(char **)a, *(char**)b); // this is what I think is correct command, but it causes segfault.
return strcmp(a,b); // This gives wrong result.
}
void disparray(int index,char words[10][20])
{
int f=0;
while(f<index)
{
printf("%s\n",words[f]);
f++;
}
}
But I am having problems with the qsort function and the comparing function. The output I get is not sorted in the current version of my program. This is what I get
./trial <words
one
two
three
four
five
six
seven
eight
nine
ten
0�one
three
four
five
six
seven
eight
nine
ten
how do I fix it?