C standard does not allow you to cast a function pointer to void*
. In order to store function pointer in a list, you need to define a field in the struct
to be of the function pointer type.
One way of doing it is with a typedef
:
typedef void (*fptr_int)(int); // This defines a type fptr_int
Now you can use it in your struct
like this:
typedef struct elem {
struct elem *next;
fptr_int *function;
} *elem;
Assign it the way you did in your example:
lst->function = &blah;
Call it as if it were a function name:
lst->function(123);
The typedef
does not need to be specific to the signature of the function that you want to store, though: any function pointer can be cast to another function pointer and back without an error. You can define a "generic" function pointer, like this
typedef void (*void_fptr)();
use it in your struct
typedef struct elem {
struct elem *next;
void_fptr *function;
} *elem;
and the use it with appropriate casts:
lst->function = (void_fptr)&blah; // Assign
...
((fptr_int)lst->function)(123); // Call