I found this sample code online, which explains how the qsort
function works. I could not understand what the compare function returns.
#include "stdlib.h"
int values[] = { 88, 56, 100, 2, 25 };
int cmpfunc (const void * a, const void * b) //what is it returning?
{
return ( *(int*)a - *(int*)b ); //What is a and b?
}
int main(int argc, _TCHAR* argv[])
{
int n;
printf("Before sorting the list is: \n");
for( n = 0 ; n < 5; n++ ) {
printf("%d ", values[n]);
}
qsort(values, 5, sizeof(int), cmpfunc);
printf("\nAfter sorting the list is: \n");
for( n = 0 ; n < 5; n++ ) {
printf("%d ", values[n]);
}
return 0;
}
In the C Programming Language, the strcmp function returns a negative, zero, or positive integer depending on whether the object pointed to by s1 is less than, equal to, or greater than the object pointed to by s2.
The comparator class compares the student to be searched from the list of students on the basis of their name attribute. If the name attribute of the object to be searched is equal to any of the object's name attribute in the list then it returns true, otherwise, it returns false.
To sort the array, use qsort() and pass a comparison function. Notes: the simple subtraction of values produces incorrect results if the difference does not fit in the int type. For example -2 and INT_MAX cannot be correctly compared with the subtraction method.
What a
and b
are is clearly stated in the documentation for qsort
: these are pointers that point to array elements that have to be compared.
Comparison function in this case knows that the array elements are of type int
. So it casts the void *
pointers to int *
type and performs a tri-state comparison of the pointed int
values by subtracting the second from the first.
It will work properly for your set of values, but in general case using subtraction for tri-state comparison is a bad programming practice, since it is prone to overflow. Also, the function in your sample code unnecessarily casts away the constness of the pointed values.
A better alternative would be
int cmpfunc(const void *a, const void *b)
{
const int *A = a, *B = b;
return (*A > *B) - (*A < *B);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With