in my homework ı couldn't understand this parameter ;
set_maker(LINKEDSTACK stack, int (*cmp) (void*, void*))
can anybody explain this using?
thank you for helping.
It is a pointer to a function taking two pointer arguments and returning an int
. Judging from its name, the semantics of the function are that it compares the two objects pointed to and returns a value <0, 0 or >0 indicating the relative order of the two object according to some ordering criteria.
The purpose of such a parameter is to allow the function (set_maker()
in this case) to operate on objects of arbitrary type and ordering rules. For example if you were operating in int
objects, you might have a function:
int icompare(const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
Then you could call set_maker()
thus:
set_maker( istack, icompare ) ;
so that set_maker()
can operate on a LINKEDSTACK
of int
s. (I'm making a somewhat reasoned guess here since you have provided no details of set_maker()
or LINKEDSTACK
).
Equally the comparison function could operate on struct
objects with more complex comparison rules involving multiple members. So its purpose is to make set_maker()
flexible enough to handle any data type without duplicating a great deal of code by providing the rules for handling each data type in the provided function.
A standard library example of such a function is qsort(), although you will notice there that the parameters are of type const void*
which is best practice for functions that are not intended to modify the objects referenced.
In C such functions like bsearch and qsort that deal with ordered sequences need a function that will compare elements of arrays.
A pointer to such a function is declared like
int ( *cmp )( const void *, const void * )
It accepts as arguments pointers to two objects that will be compared. Within the function the pointers after casting to the required type are dereferenced and the pointed objects are compared.
The function shall return an integer less than, equal to, or greater than zero if the first pointed object is considered, respectively, to be less than, to match, or to be greater than the second pointed object.
It seems that the function set_maker
uses within its body such a comparison function to make comparison between two objects for example for ordering them.
.
set
, notstack
? Or it is a stack where you can remove duplicate elements? – Eugene Sh.