First, you're a bit inconsistent in when and how you use argc or argc-1 and argv or argv+1 (or, you were in your last complete post, #14). Pick one method and stick to it. I recommend your functions don't try to adjust anything by +/- 1, that way they will work generically for any array of char *, should you want to reuse your print or sort functions. Always correct for this in main by passing in argc-1 and argv+1 to the functions. This effectively passes in a sub-array that starts at argv[1] instead of argv[0].
Code:
// in main
printf("Before sorting:\n");
print_array(argc-1, argv+1); // adjusted in main
sort_in_order (argc-1, argv+1); // adjusted in main
printf("\nIn order:\n");
print_array(argc-1, argv+1); // adjusted in main
...
void print_array(int argc, char * argv[]){
int i;
for( i = 0; i < argc; i++){ // note, start at 0 and go up to < argc, don't try to skip the first element here, you've already adjusted in main
printf("%s\n", argv[i]);
}
}
All those *s before temp, argv[i] and argv[j] are the problem. Remember, temp, argv[i] and argv[j] are pointers to char, so putting a * in front of them dereferences that pointer and gives you the single char it points to, i.e. the first letter of each argument. As a side note, temp is a pointer, but it is never set to point to valid memory, so when you do the following:
Code:
*temp = argv[i];
argv[j] = *temp;
You are reading from and writing to memory you might not own or have access to. This results in undefined behavior, which may mean a crash/seg fault, garbled output, or any number of other things. Never dereference a pointer unless it points somewhere valid.
Go back and look at post #10. Your compare and swap were correct there, but I think your sorting loops were wrong. You did
Code:
for(i = 1; i < argc-1; i++ ){
for(j = i+1; j < argc-1; j++){
You need to start i at 0, since you skip first element by passing in argv+1. Also, you need to stop at i < argc-1, since j = i+1, and this will cause a buffer overflow on the last iteration, where you will be comparing/sorting/swapping garbage. j, on the other hand, should start at i+1, and stop at j < argc. That makes j iterate over all elements after i.
Code:
for (i = 0; i < argc - 1; i++) {
for (j = i + 1; j < argc; j++) {
That should about do it.