Thread: problem with qsort()

  1. #1
    the c-dil
    Join Date
    May 2005
    Posts
    12

    Unhappy problem with qsort()

    // program to sort numbers using qsort library routine


    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <conio.h>
    #include <search.h>
    
    int sort_function( const void *a, const void *b);
    
    
    int list[8] = { 12,34,56,2023, 3445,223, 5454,4 };
    
    int main(void)
    {
       int  x;
    
       clrscr();
       qsort((void *)list, 8, 2, sort_function);
       for (x = 0; x < 8; x++)
          printf("%d\n", list[x]);
     //  return 0;
       getch();
    }
    
    int sort_function(const void *a, const void *b)
    {
     int x,y;
    
      // return( strcmp((int *)a,(int *)b) );
     if(b<a)
      return (-1);
      else
      return (1);
      
    }
    OUTPUT IS COMING OUT TO BE

    223
    34
    12
    4
    56
    5454
    2023
    3445

    // The problem is definitely with the sort function. I tried to return a and b instead of 1 and -1 but with no change . please help me out

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    And what old compiler are you using?

    > qsort((void *)list, 8, 2, sort_function);
    Should be
    qsort( list, 8, sizeof(list[0]), sort_function);

    > int sort_function(const void *a, const void *b)
    These two pointers are in effect things like &list[0] and &list[4]
    Ie, pointers to two elements of your array which need to be compared.
    So the first thing to do is cast these void pointers back into int pointers
    Then dereference those pointers to compare two actual elements of the array
    Code:
    int sort_function(const void *a, const void *b)
    {
      const int *pa = a;
      const int *pb = b;
      if ( *pa < *pb ) return -1;
      if ( *pa > *pb ) return 1;
      return 0;
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Someone having same problem with Code Block?
    By ofayto in forum C++ Programming
    Replies: 1
    Last Post: 07-12-2007, 08:38 AM
  2. A question related to strcmp
    By meili100 in forum C++ Programming
    Replies: 6
    Last Post: 07-07-2007, 02:51 PM
  3. WS_POPUP, continuation of old problem
    By blurrymadness in forum Windows Programming
    Replies: 1
    Last Post: 04-20-2007, 06:54 PM
  4. Laptop Problem
    By Boomba in forum Tech Board
    Replies: 1
    Last Post: 03-07-2006, 06:24 PM
  5. Replies: 5
    Last Post: 11-07-2005, 11:34 PM