Reputation: 85
I'm trying to create a function variable that point to a function that can be passed to the qsort()
function, and I received an "assignment type mismatch" error when I tried to run the below codes.
int compareFunc (const void * a, const void * b)
{
//codes
}
int main(void) {
int *ptr; //create a function pointer variable that point to compareFunc
ptr = &compareFunc //Initialize function pointer
//codes
return 0;
}
Could someone please tell me what I did wrong and explain what exactly is const void *
?
Upvotes: 0
Views: 418
Reputation: 70931
Do a man qsort
and you'll get (besides more):
void qsort(void *base, size_t nmemb, size_t size,
int(*compar)(const void *, const void *));
The emphasised part obviously has to be what you are looking for.
Upvotes: 0
Reputation: 3489
Your declaration of function pointer is incorrect. You are declaring a regular pointer. The syntax of a function pointer declaration is :
<return_type> (* func_ptr_Variable_name) ( [params...] )
The function pointer should be :
int main(void){
int (*ptr)(const void *,const void *);
ptr = compareFunc; //'&' is not needed here, function name is automatically converted to its address
...
return 0;
}
const void *
simply means that the data pointed to by the void *
pointer cannot be modified in the function.
Upvotes: 0
Reputation: 1847
Your declaration of pointer isn't a function pointer. It's just a regular pointer. It should be changed to declare a function pointer as follows.
int (*fptr) (const void *a, const void *b);
fptr = compareFunc;
For function pointers you never have to take the address explicitly using the & operator.
Also const void *
means that the object/data pointed to by the pointer will not be modified in that function. So compiler will raise an error whenever you perform a write operation on the value the pointer points to.
Upvotes: 2
Reputation: 274
a function pointer is declared like this:
return_type (* variable_name)(params)
So in your case:
int (*cfptr)(const void * a, const void * b);
cfptr = compareFunc;
Upvotes: 1
Reputation: 122383
Because int *
is a type of object pointer, not a function pointer.
You can declare it as int (*ptr)(const void *,const void *);
, or use typedef
to simplify declaring function pointers:
typedef int (*comptr)(const void *a, const void *b);
int compareFunc (const void * a, const void * b)
{
//codes
}
int main(void) {
comptr ptr;
ptr = compareFunc;
//codes
return 0;
}
Also note that instead of ptr = &compareFunc;
, you can omit the &
because the function name is converted to a function pointer automatically.
Upvotes: 0