-
qsort problem
I was trying to understand pointers to functions and came across qsort program
can you guys tell me how the compare function "record_compare" works
given the function
Code:
typedef struct {
int key;
} Record
and
Code:
int record_compare (void cons *a, void const *a)
{ return ( ((Record *)a)->key - ((Record *)b)->key);
}
-
The function takes in two void * constants. As you can not dereference a void point you have to cast it to the correct type.
So (Record *)a casts a as a Record pointer. -> is the short hand to dereference a point to a structure or union and get a member.
The function needs to return 0 if they are equal, greater then 0 if the first one is greater, or less then 0 if the second one is greater. Since you are really comparing two integer values by subtracting the second from the first you get those ranges.
-
very neatly put, thantos.
-
>Since you are really comparing two integer values by subtracting the second from the first you get those ranges.
...except that this technique will fail to produce correct results if there is integer overflow.