I need to create a program that sorts command line strings. (Example output under code) This is the code I have so far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int stringcomp (const void * x, const void * y);
int main(int argc, char *argv[]){
int i,j;
int k = 1;
char strings[argc-1][20];
strcpy(strings[0], argv[1]);
for(i=2; i< argc-1; i++){
strcat(strings[k],argv[i]);
k++;
}
qsort(strings, argc, 20, stringcomp);
for(j=0 ; j < argc-1; j++){
printf("%s ", strings[j]);
}
return 0;
}
int stringcomp (const void *x, const void *y) {
return (*(char*)x -*(char*)y);
}
This is what I type into the command line: ./inOrder hello darkness my old friend
This is what I should get: darkness friend hello my old
But this is what I keep getting: ?darkness ?old ]@my
What am I doing wrong?
strings[k]is uninitialized and thus cannot use it instrcat.stringcomp()function when thestrcmp()library function already does what you want? Or if you do write your ownstringcomp()(perhaps because, technically,strcmp()does not have the correct parameter types) then why are you not just using that to implement your own comparison?charfor your temp array instead of a 1D array ofchar *? Not only would the latter help you avoid some initialization pitfalls, it would also remove the current 20-charlimit on the strings you can sort.