The question pretty much says it all.
I’m not sure how to do this and haven’t come anywhere near anything that works.
Here’s some example functions:
add(int x, int y) {
return x+y;
}
and,
mean(int x1, int y1, int x2, int y2) {
return (x1 + y1 + x2 + y2) / 4;
}
So far I’ve tried using typedef with both, but I can’t figure how to make something point to one of either type:
typedef int (*mathfunc2)(int x, int y);
typedef int (*mathfunc4)(int x1, int y1, int x2, int y2);
????? func_table[2] = {add, mean};
You need to pick a function pointer type to use as a “generic function pointer”, use that type to define your array, and use explicit casts. Casting one function pointer type to another and then back again is guaranteed to preserve the value.
In other words:
Then to call
add, you need to cast it back to the right type:You can define some macros if you find it more palatable: