unable to understand the syntax in c

when i was going through the library/header file of c ,in stdlib.h -> qsort function ,
in example section of this page http://www.cplusplus.com/reference/cstdlib/qsort/
i am unable to understand the syntax of ( *(int*)a - *(int*)b ); in the compare function.
please help me to understand.


The compare function, as it is implemented, receives as arguments two void pointers or “pointers to void elements”, namely:

int compar (const void* p1, const void* p2);

as such, this ensures that the comparison function can be used with any type of arguments by doing an appropriate typecast.

On the case where the elements being compared are integers, this can be done with:

 ( *(int*)a - *(int*)b );

where the syntax (int*)a is the pointer typecast syntax.

The other * symbols are to indicate that the function receives pointers to the elements and not the elements themselves.

The relative ordering is then done based on the result of the subtraction. You can refer to the link you provided yourself for more information.

Best regards,


1 Like