# problem with qsort()

• 06-01-2005
rajatkochhar
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
• 06-01-2005
Salem
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; }```