I have written a program which could sort 5 strings you inputed from small to big. However, it can’t work. I have worked at it for almost an hour, but I couldn’t find out the problem. Here is the code.
#include <stdio.h>
#include <string.h>
main() {
char *sz[5], *temp;
int i, j;
for(i = 0; i < 5; i++) {
gets(sz[i]);
fflush(stdin);
}
for(i = 0; i < 5; i++) {
for(j = i+1; j < 5; j++) {
if(strcmp(sz[i], sz[j]) > 0) {
temp = sz[i];
sz[i] = sz[j];
sz[j] = temp;
}
}
puts(sz[i]);
puts("");
}
}
First huge problem is that you are using a routine that should never have existed, and using it improperly:
You did not allocate any storage for
gets()to store into, so it is simply scribbling on unrelated memory. (This often leads to security problems.)You should pay special attention to the
BUGSsection in your manpages:Unlearn
gets(3), now, and be a happier programmer.Use
malloc()to allocate some memory for those character arrays.Ignacio hit another problem squarely on the head — you’re printing before your sort is finished. Add another loop to print, after the sorting. (Better yet, put the input, sort, and output into three separate functions. Perhaps you’re not there yet, but it would be well worth doing this sooner rather than later, as it makes testing your programs significantly easier to have printing functions you can use for debugging.)