Reputation: 215
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?
Upvotes: 0
Views: 281
Reputation: 206567
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);
Upvotes: 2
Reputation: 10184
You are printing your input, not the sorted result. Note the line:
printf("%s\n",str);
should be
printf("%s\n",sorted_str);
Upvotes: 4