How can I cast a void function pointer in C?
Consider:
#include <stdio.h>开发者_开发知识库
int f() {
return 20;
}
int main() {
void (*blah)() = f;
printf("%d\n",*((int *)blah())()); // Error is here! I need help!
return 0;
}
I want to cast 'blah' back to (int *) so that I can use it as a function to return 20 in the printf
statement, but it doesn't seem to work. How can I fix it?
This might fix it:
printf("%d\n", ((int (*)())blah)() );
Your code appears to be invoking the function pointed to by blah
, and then attempting to cast its void
return value to int *
, which of course can't be done.
You need to cast the function pointer before invoking the function. It is probably clearer to do this in a separate statement, but you can do it within the printf call as you've requested:
printf("%d\n", ((int (*)())blah)() );
Instead of initializing a void pointer and recasting later on, initialize it as an int pointer right away (since you already know it's an int function):
int (*blah)() = &f; // I believe the ampersand is optional here
To use it in your code, you simply call it like so:
printf("%d\n", (*blah)());
typedef
the int version:
typedef int (*foo)();
void (*blah)() = f;
foo qqq = (foo)(f);
printf("%d\n", qqq());
精彩评论