c - Explain typedef for function used in qsort library -


i using qsort library function sort array of structure elements, while searching on internet found resource: info: sorting structures c qsort() function @ support.microsoft.

i understand qsort function requires typecast generic pointers.

however not able line:

typedef int (*compfn) (const void*, const void*); 

which has been declared, , 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 compare function  ); 
  1. how typedef behaving, mean have typedeffed int (*compfn) or int (compfn)?
  2. if former, shouldn't call (*compfn)?

syntax:

typedef  int (*compfn)  (const void*, const void*);   ^      ^       ^            ^          ^   | return type  |               arguments type   |             new type name    defining new type 

compfn new user defined type defined typedef keyword,

so, have typedefded int (*)(const void*, const void*); comfn using syntax described above.

a declaration:

 compfn  fun; // same as: int (*fun)  (const void*, const void*); 

means fun function pointer takes 2 arguments of const void* types , returns int.

suppose have function like:

int xyz  (const void*, const void*);     

then can assign xyz address fun.

fun = &xyz;  

at calling qsort():

in expression (compfn)compare, typecasting function compare (compfn) type function.

a doubt:

shouldn't call (*compfn).

no, type name not function name.

note: if writing int (*compfn) (const void*, const void*); without typedef comfn pointer function returns int , take 2 arguments of type const void*


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

html - Unable to style the color of bullets in a list -

c# - must be a non-abstract type with a public parameterless constructor in redis -