user188276
user188276

Reputation:

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?

Upvotes: 0

Views: 6243

Answers (4)

Dave Costa
Dave Costa

Reputation: 48111

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)() );

Upvotes: 3

Foo Bah
Foo Bah

Reputation: 26251

typedef the int version:

typedef int (*foo)();

void (*blah)() = f;
foo qqq = (foo)(f);

printf("%d\n", qqq());

Upvotes: 1

FelixCQ
FelixCQ

Reputation: 2028

This might fix it:

printf("%d\n", ((int (*)())blah)() ); 

Upvotes: 4

Manny D
Manny D

Reputation: 20714

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)());

Upvotes: 1

Related Questions