I understand this C function (qsort comparison function)?

I am trying to use qsort from stdlib.h . Qsort requires a comparison function argument doing this:

int (*compar)(const void *, const void*)

      

Am I reading it correctly as: "a pointer to a returning function f. F must take two arguments that are shared pointers"? I'm not sure about the meaning of the parentheses around '* compare' - is there a name for this that I can find?

The link provides an example:

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

      

I would correctly read * (int *) a as "dereferencing the value of a after it has been selected as a pointer to an integer"?

Greetings.

+3


source to share


3 answers


Am I reading this correctly as: "a pointer to an int-return function f. F should take two arguments that are shared pointers"?

Right.

I'm not sure about the meaning of the brackets around *compar

This is the syntax for declaring function pointers (called "function pointers"). Without partners, this would be a function declaration



// Declares a function named compar. (It returns an int*.)
int *compar(const void *, const void*);

// Declares a function pointer named compar. (The func returns an int.)
int (*compar)(const void *, const void*);

      

Would I correctly read *(int*)a

as "dereference the value of a after it has been passed as a pointer to an integer?"

Return again. He gives int

the address a

.

+8


source


You are on the right track.

In the first example, compar

called a function pointer . The element ()

is part of the function pointer syntax.

Note that without explicitly ()

around *compar

, it compar

will be treated as a fucntion, returning int *

, taking two pointers void

.

In the second case, for the binary subtraction operator -

from the standard C99

, chapter 6.5.6, clause 3,



- both operands are of arithmetic type;

- both operands are pointers to qualified or unqualified versions of the compatible object types; or

- the left operand is a pointer to the type of the object, and the right operand is of an integer type. (Reducing is equivalent to subtracting 1.)

and for the first point, arithmatic type

from chapter 6.2.5, paragraph 18,

Integer and float types are collectively called arithmetic types.

So, before using pointers for subtraction, they are cast to a pointer int

, then dereferenced, and the value (s) are used (used) as operands for integer subtraction.

+4


source


Yes. You understand the correct syntax. The parentheses ()

around *compar

indicate that it compar

is a function pointer. In the absence of this, the meaning will be completely different.

+1


source







All Articles