I am trying to do something like this:
void print (int number)
{
printf("Argument \"%i\" has been given", number);
}
void foo (void (*ptr)(int arg))
{
ptr(arg);
}
int main (void)
{
foo(print(10));
return 0;
}
Unlikely this will work, because print(10)
should return void, not an actual function address.. but at least I hope my question is understandable as it is very hard for me to explain it with plain words.
How do I transfer arguments in a function pointer like that?
You cannot "transfer arguments in a function pointer like that". What you can do instead is pass an additional argument that match the argument expected by your function pointer.
This would looks like this:
void print (int number)
{
printf("Argument \"%i\" has been given", number);
}
void foo (void (*ptr)(int), int arg) // the new argument is here.
{
ptr(arg);
}
int main (void)
{
foo(print, 10);
return 0;
}
What we are doing here is packing the argument and the function pointer together in a struct, and passing this struct to foo()
. This is a bit similar to c++'s std::bind
but simplified and less powerful.
typedef struct bind_s
{
void (*ptr)(int);
int arg;
} bind_t;
void print (int number)
{
printf("Argument \"%i\" has been given", number);
}
void foo (bind_t call)
{
call.ptr(call.arg);
}
int main (void)
{
bind_t call = {print, 10};
foo(call);
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.