I am using qsort library function to sort an array of structure elements, while searching on the Internet I found a resource: INFO: Sorting Structures with the C qsort() Function @ support.microsoft.
I understand that qsort function requires to be typecast by generic pointers.
However I am not able to get this line:
typedef int (*compfn) (const void*, const void*);
Which has been declared, and its subsequent call:
qsort((void *) &array, // Beginning address of array
10, // Number of elements in array
sizeof(struct animal), // Size of each element
(compfn)compare // Pointer to compare function
);
- How is
typedef
behaving, I mean what exactly have we typedeffedint (*compfn)
orint (compfn)
? - If the former, then shouldn't the call be
(*compfn)
?
The
typedef
declaration creates an alias for a specific type. This means it can be used as any other type in declarations and definitions.So if you have e.g.
Then you can declare a variable or argument using only
compfn
instead of the whole function pointer declaration. E.g. these two declarations are equal:Both creates a function pointer variable, and the only difference is the name of the variable name.
Using
typedef
is common when you have long and/or complicated declarations, to easy both your writing of such declarations and to make it easier to read.It is a type of a function pointer. The function which is being pointed to returns
int
and accepts twoconst void*
parameters.Syntax:
compfn
is a new user definedtype
defined bytypedef
keyword,So, you have exactly typedefded
int (*)(const void*, const void*);
tocomfn
using the syntax I described above.A declaration:
means
fun
is a function pointer that takes two arguments ofconst void*
types and returnsint
.Suppose you have a function like:
then you can assign
xyz
address tofun
.At calling
qsort()
:In expression
(compfn)compare
, you are typecasting a functioncompare
to(compfn)
type function.A doubt:
No, its type name not function name.
Note: if you just writing
int (*compfn) (const void*, const void*);
without typedef thencomfn
will be a pointer to a function that returnsint
and take two arguments of typeconst void*