What does this code do?

hello,

Can someone please explain what the 2 lines of code do?

1
2
    int first = *(int*)first_arg;
    int second = *(int*)second_arg;


this is the rest of the program
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
  void qsort(void *base, size_t nmemb, size_t size,
            int(*compar)(const void *, const void *));

#include <stdlib.h>

int int_sorter( const void *first_arg, const void *second_arg )
{
    int first = *(int*)first_arg;
    int second = *(int*)second_arg;
    if ( first < second )
    {
        return -1;
    }
    else if ( first == second )
    {
        return 0;
    }
    else
    {
        return 1;
    }
}

int main()
{
    int array[10];
    int i;
    /* fill array */
    for ( i = 0; i < 10; ++i )
    {
        array[ i ] = 10 - i;
    }
    qsort( array, 10 , sizeof( int ), int_sorter );
    for ( i = 0; i < 10; ++i )
    {
        printf ( "%d\n" ,array[ i ] );
    }

}



casting first_arg to an integer pointer, and then dereferencing that pointer to get a value (i.e. int first).
void pointers can be used to pass around different stuff:
http://www.learncpp.com/cpp-tutorial/613-void-pointers/

The first_arg is a pointer to const void object. The (int*) is a cast that the object is actually an int, i.e. the first_arg is temporarily a pointer to int.

Dereferencing a pointer returns the pointed to value.
thx ;)
Topic archived. No new replies allowed.