I have one function:
int compare(char * c1, char * c2){
...
...
}
What are the various styles in which I can write a function int ret_compare(void * item)
that returns a pointer to compare?
There are two main styles, one using a typedef
and one not (with two variants of the typedef
). Your comparator should take constant pointers, as below:
int compare(const char *c1, const char *c2) { ... }
// Raw definition of a function returning a pointer to a function that returns an int
// and takes two constant char pointers as arguments
int (*ret_compare1(void *item))(const char *, const char *)
{
// Unused argument - item
return compare;
}
// More usual typedef; a Comparator2 is a pointer to a function that returns an int
// and takes two constant char pointers as arguments
typedef int (*Comparator2)(const char *, const char *);
// And ret_compare2 is a function returning a Comparator2
Comparator2 ret_compare2(void *item)
{
// Unused argument - item
return compare;
}
// Less usual typedef; a Comparator3 is a function that returns an int
// and takes two constant char pointers as arguments
typedef int Comparator3(const char *, const char *);
// And ret_compare3 is a function returning a pointer to a Comparator3
Comparator3 *ret_compare3(void *item)
{
// Unused argument - item
return compare;
}
Note that these comparators cannot be used with bsearch()
and qsort()
(unless you use fairly gruesome casts) because those comparators are expected to take const void *
arguments.
Note, too, that for comparing strings, as opposed to single characters, the function used by qsort()
or bsearch()
should be similar to:
int string_comparator(const void *v1, const void *v2)
{
const char *s1 = *(char **)v1;
const char *s2 = *(char **)v2;
return(strcmp(s1, s2));
}