Did you find
this link?
It pretty much explains it, however qsort has this prototype
-
void qsort(void * base,
-
size_t num,
-
size_t size,
-
int ( * comparator ) ( const void *, const void * ) );
-
It takes 4 parameters and it sorts an array of any sized elements using a comparison function provided by the user (caller).
The first 3 parameters are a pointer to the first element of the array, the number of elements in the array and the size of each element in the array. This information basically allows the function to correctly address every element of the array without having to know the type of the array elements.
Because qsort has no knowledge of the type of each array element it does not know how to compare them. It gets round this by having the caller passing a pointer to a function that will compare 2 elements of the array and return a result, less than, equal or greater than.
This function takes 2 parameters, these are pointer to array elements and are passed as void *. They should be cast to a pointer to the array element type, then the function should perform the comparison on the 2 elements and return <0 is parameter1 < parameter2, 0 if parameter1 == parameter2 and >0 if parameter1 > parameter2.
-
#include <stdlib.h>
-
#include <stdio.h>
-
#include <time.h>
-
-
static const int HIGHLIMIT = 100;
-
-
static int CompFn(const void *op1, const void *op2);
-
-
int main(int argc, char **argp)
-
{
-
int array[10];
-
int ix;
-
int interval = RAND_MAX / HIGHLIMIT;
-
int rand_max = interval * HIGHLIMIT;
-
-
-
srand((unsigned)time(NULL));
-
-
printf("List : ");
-
-
for(ix=0; ix<sizeof array/sizeof array[0]; ix++)
-
{
-
array[ix] = (rand() % rand_max) / interval + 1;
-
-
printf("%3d ", array[ix]);
-
}
-
-
putchar('\n');
-
-
qsort(array, sizeof array/sizeof array[0], sizeof array[0], CompFn);
-
-
printf("Sorted: ");
-
-
for(ix=0; ix<sizeof array/sizeof array[0]; ix++)
-
{
-
printf("%3d ", array[ix]);
-
}
-
-
putchar('\n');
-
-
return EXIT_SUCCESS;
-
}
-
-
int CompFn(const void *op1, const void *op2)
-
{
-
return *(int *)op1 - *(int *)op2;
-
}
-