Thread: qsort function

  1. #1
    Registered User
    Join Date
    Mar 2004
    Posts
    41

    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 ???

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    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.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 05-13-2011, 08:28 AM
  2. In over my head
    By Shelnutt2 in forum C Programming
    Replies: 1
    Last Post: 07-08-2008, 06:54 PM
  3. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  4. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  5. Replies: 5
    Last Post: 02-08-2003, 07:42 PM