# Thread: qsort - newbie trouble with pointers

1. ## qsort - newbie trouble with pointers

This is a qsort sample function i found on google.

Code:
```/* qsort example */
#include <stdio.h>
#include <stdlib.h>

int values[] = { 40, 10, 100, 90, 20, 25 };

int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}

int main ()
{
int * pItem;
int n;
qsort (values, 6, sizeof(int), compare);
for (n=0; n<6; n++)
{
printf ("%d ",values[n]);
}
return 0;
}```
But I couldn't understand the function compare.
Why void? Why *(int*)a ?
Actually I'm coding a program and I wouldn't use pointers yet until I understand it. But I presume that is impossible to use qsort function without using pointers. I don't like to import lines to my code without know as it works. "Copy and paste" is a lammer/newbie way. Please, help me to understand this function.

2. qsort() is a generic algorithm - it does not care what it is actually sorting. In order to be generic, it has to use generic pointers - void*. So, you can use it to sort chars, strings, or an array of struct Employees.

3. Code:
```int a = 5;
void *p = (void*)&a; //cast the address to a to a pointer to void
int *pa = (int*)p; //cast p back to a pointer to int
...
printf("%d",*pa); //dereference pa, to get 5```
gg

4. >But I couldn't understand the function compare.
>Why void? Why *(int*)a ?

The function qsort() requires a compare-function to compare two elements, this compare-function must be written by yourself. Because the qsort() function is a generic sort-function, which means that it must be able to sort arrays of various types, it must make use of void-pointers.

Because you make use of void-pointers, you must cast the pointers to the appropriate types to be able to compare. That is the casting *(int *)a. It casts the generic pointer to a pointer to int and then gets the object pointed to.

>But I presume that is impossible to use qsort function without >using pointers.

Yes, you need to know about pointers. Not only "normal" pointers, also about function pointers. Tutorials about function pointers can be found here.

http://www.newty.de/index.html

>qsort (values, 6, sizeof(int), compare);

Here the function compare() is in the function call to qsort, note that this is an example of the use of function pointers. If you want to use qsort() for another array of a different type, for example an array of structs, then you need to write a compare function for that type and pass the pointer to that function to qsort().

5. thank you very much guys!