-
qsort function
Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int comp_nums(const int *num1, const int *num2)
{
if (*num1 < *num2) return -1;
if (*num1 == *num2) return 0;
if (*num1 > *num2) return 1;
}
int main(){
char numbers[] = "afbdc";
qsort(numbers,5,sizeof(int),(void *)comp_nums);
printf("%s\n", numbers);
}
i would like to know whats wrong with my code ?? Why cant i sort the following string as "abcdf" and print it out?? which part did i do wrong ???
-
You're calling the function wrong, you're ignoring your compiler's warnings, and most importantly, you're telling it the items are all a different size than they really are:
Code:
#include <stdlib.h>
#include <stdio.h>
int comp_nums(const void *num1, const void *num2)
{
return (*((const char*)num1)<*((const char*)num2)?-1
:*((const char*)num1)>*((const char*)num2)?1
:0);
}
int main()
{
char numbers[] = "afbdc";
qsort(numbers,5,sizeof(char),comp_nums);
printf("%s\n", numbers);
return 0;
}
Quzah.