I am having difficulty in passing a function as void*
with its argument also void*
:
#include <stdlib.h>
void* hello(void* (*calc)(void *), void* op){
int val = *(int *) op;
int* retval = malloc(sizeof(int));
*retval = calc(val);
return retval;
}
int calc(int b){
int a = 5;
int sum = a+b;
return sum;
}
int main(){
int arg = 4;
int value = *(int*) hello(&calc,&arg);
return 0;
}
The error is:
40392282.c: In function ‘hello’: 40392282.c:6:20: warning: passing argument 1 of ‘calc’ makes pointer from integer without a cast [-Wint-conversion] *retval = calc(val); ^~~ 40392282.c:6:20: note: expected ‘void *’ but argument is of type ‘int’ 40392282.c:6:13: warning: assignment makes integer from pointer without a cast [-Wint-conversion] *retval = calc(val); ^ 40392282.c: In function ‘main’: 40392282.c:19:31: warning: passing argument 1 of ‘hello’ from incompatible pointer type [-Wincompatible-pointer-types] int value = *(int*) hello(&calc,&arg); ^ 40392282.c:3:7: note: expected ‘void * (*)(void *)’ but argument is of type ‘int (*)(int)’ void* hello(void* (*calc)(void *), void* op){ ^~~~~ 40392282.c:19:9: warning: unused variable ‘value’ [-Wunused-variable] int value = *(int*) hello(&calc,&arg); ^~~~~
Any suggestions of how to actually pass a function as an argument whose type is void*
?
Thank you @2501, but I am getting the following error.
hello.c: In function ‘hello’:
hello.c:12:18: warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]
int(*calc)(int) =calc_call;
^
hello.c: In function ‘main’:
hello.c:34:35: warning: passing argument 1 of ‘hello’ from incompatible pointer type [-Wincompatible-pointer-types]
int value = *(int *) hello(&calc,&arg);
^
hello.c:10:7: note: expected ‘void * (*)(void *)’ but argument is of type ‘int (*)(int)’
void* hello(void* (*calc_call)(void *), void* op){
when I am writing the code as:
void* hello(void* (*calc_call)(void *), void* op){
int* const integer = op;
int(*calc)(int) =calc_call;
*integer=calc(*integer);
return op;
}
int calc(int b){
int a = 5;
int sum = a+b;
return sum;
}
int main(){
int arg = 4;
int value = *(int*) hello(&calc,&arg);
return 0;
}