I want to know how this function is working. I used qsort() function to sort the integers in an array and i found this compare() function on internet. It worked perfectly well but i cannot understand how is it working and what's its logic. Any help?

int compare (const void * a, const void * b)
{
  return ( *(int*)a - *(int*)b );
}
if a>b returns +ve
else if a==b returns 0
else if a<b returns -ve

I can't understand the syntax still.

int compare (const void * a, const void * b)
The two values 'a' and 'b' are of type void pointer and we want this function to compare two integers so we must convert from void pointers to integers.

To do this we first cast the void pointer into an integer pointer.
(int*)a This leaves us with a pointer to an integer

Next we want to get the value in which the integer pointer is looking at by dereferencing the pointer with '*'.

*(int*)a This will convert the void pointer into an integer pointer, then dereference the integer pointer and leave us with an integer.

You could break this up in such a way that it is very clear to see what is going on but basically all that is happening here is a cast and a dereference all done on one line.

qsort calls the compare function with pointers to the values as arguments. Since qsort can work with any type of array, those pointers are void pointers. So a comparison function given to qsort must take two (const) void pointers as arguments.

So that's why the signature of compare looks like it does. In the body it then simply casts the void pointers to int pointers (because the compare function knows that the values you're trying to compare are really ints), dereferences them and subtracts the second value from the first.

So the function simply compares two integers by subtracting the second from the first. This will cause a negative number to be returned if the first number is the smaller one, 0 if both are equal and a positive number if the second number is the larger one, which is exactly what's expected of a comparison function given to qsort.

so it means that if i have an array of strings or of characters, i just have to cast the pointers to the respective type in the compare function and it will work, doesn't it?

You also need to change the call to qsort to use sizeof(char) instead of sizeof(int), but yes, for chars all you need to change in the compare function is to replace int* with char* when casting the pointers.

For strings you'd want a different logic in the compare function though. If you'd just subtract the strings from each other, you'd sort by the pointer values, which is rarely what you want. So you'd cast the void pointers to char**, then dereference those and pass the resulting char*s to strcmp, so that it compares the contents of the strings.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.