0

I'm trying to use qsort to sort the characters in a single string. It just doesn't seem to work. This is my code.

int compare_function (const void* a, const void* b) { char f = *((char*)a); char s = *((char*)b); if (f > s) return 1; if (f < s) return -1; return 0; } int main(int argc, char* argv[]) { char* str= argv[1]; /* Originally missing the +1 */ char* sorted_str = malloc((strlen(str) + 1)*sizeof(char)); memcpy(sorted_str, str, strlen(str) + 1); qsort(sorted_str, sizeof(str)/sizeof(char), sizeof(char), compare_function); printf("%s\n", sorted_str); // Originally str free(sorted_str); return 0; } 

The output is ?. What do I need to do to fix this?

2
  • 1
    Lots of mistakes here. As pointed out in the comments on an answer, you're not accounting for the NULL termination when allocating memory for your sorted string. You are passing in the wrong number of elements, as you have sizeof(str) / sizeof(char), and str is a character pointer, so its size is only the number of bytes to store a pointer address. You never check to see whether you had enough arguments passed in...are you sure you passed in an argument and it's in the right spot? Commented May 22, 2015 at 2:53
  • 2
    Note that it is not entirely fair to change the code so that an answer that validly points out one of the problems ceases to be relevant. You can either annotate the modified code (as I've done for you) or leave the original and add the revised code. Commented May 22, 2015 at 3:03

2 Answers 2

4

You are printing your input, not the sorted result. Note the line:

printf("%s\n",str); 

should be

printf("%s\n",sorted_str); 
Sign up to request clarification or add additional context in comments.

4 Comments

I made that change, really stupid of me. But now it gives no output at all.
You probably need to increase the initial allocation/copy of memory by one character to allow for the null terminator, although you're really not treating it like a string - just a char array...
did that, now getting a ? as output. Sadly I can't even get gdb to work on my Mac and hence can't debug.
R Sahu got it. Darn! :)
2

The second argument to qsort is not right.

qsort (sorted_str, sizeof(str)/sizeof(char), // sizeof(str) is size of a pointer. sizeof(char), compare_function); 

You need:

qsort (sorted_str, strlen(str), sizeof(char), compare_function); 

1 Comment

HATE it when I miss obvious stuff like that. Good luck! :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.