You are using a version without Ads of this website. Please, consider donating:

### Using qsort I Don't Understand?

So I understand basic pointers etc. but I don't get how you're quite supposed to read this. So in the example on this website:

 ``12345678910111213141516171819`` ``````/* qsort example */ #include /* printf */ #include /* qsort */ int values[] = { 40, 10, 100, 90, 20, 25 }; int compare (const void * a, const void * b) { return ( *(int*)a - *(int*)b ); } int main () { int n; qsort (values, 6, sizeof(int), compare); for (n=0; n<6; n++) printf ("%d ",values[n]); return 0; }``````

So I understand the function essentially but I don't understand how to read nor do I understand how the part of the code works that is:

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

So here we are pointing to an int which is pointing to itself at a? I don't get it what is (int*).

Also why the parentheses what does this mean? It looks like a cast but that doesn't make sense either? This is confusing can someone explain please? Thanks guys!
`(int*)` is a C-style cast to pointer-to-integer. Since the function accepts a void pointer you need to cast it to something with known data width before dereferencing it.
Last edited on
If you spend a little time with sort algorithms you realise that although the algorithms vary, the swap and the compare functions is all that's different for sorting different types.

Your example is sorting an array of ints. And the compare method finds the difference of the two numbers.

If this were C++, qsort would be a templated function. But qsort is a C function, so the type system has be bypassed a little. In C, a compare function typically returns zero of equality, less than zero and greater than zero indicate which arg is greater. See strcmp: http://pubs.opengroup.org/onlinepubs/007908799/xsh/strcmp.html

The swap done by calling memset, but for that it needs to know the size of the type, that's why you need to pass in sizeof(int).

The compare function takes pointers to the two numbers to be compared. These are defined to be pointers to anything, void*, and you cast them to the what you know them to be.

Line 9 casts both parameters to pointers to int, then dereferences them, then compares the values. qsort calls this callback whenever it needs to compare two values.
Last edited on
Right this makes more sense now that it's dereferencing the casted pointer to an integer.
Topic archived. No new replies allowed.