How can I create a "function pointer" (and (for example) the function has parameters) in C?
http://www.newty.de/fpt/index.html
typedef int (*MathFunc)(int, int);
int Add (int a, int b) {
printf ("Add %d %d\n", a, b);
return a + b; }
int Subtract (int a, int b) {
printf ("Subtract %d %d\n", a, b);
return a - b; }
int Perform (int a, int b, MathFunc f) {
return f (a, b); }
int main() {
printf ("(10 + 2) - 6 = %d\n",
Perform (Perform(10, 2, Add), 6, Subtract));
return 0; }
This previous SO question may help you:
http://stackoverflow.com/questions/840501/how-do-function-pointers-in-c-work
typedef int (*funcptr)(int a, float b);
funcptr x = some_func;
int a = 3;
float b = 4.3;
x(a, b);
I found this site helpful when I was first diving into function pointers.
First declare a function pointer:
typedef int (*Pfunct)(int x, int y);
Almost the same as a function prototype.
But now all you've created is a type of function pointer (with typedef
).
So now you create a function pointer of that type:
Pfunct myFunction;
Pfunct myFunction2;
Now assign function addresses to those, and you can use them like they're functions:
int add(int a, int b){
return a + b;
}
int subtract(int a, int b){
return a - b;
}
. . .
myFunction = add;
myFunction2 = subtract;
. . .
int a = 4;
int b = 6;
printf("%d\n", myFunction(a, myFunction2(b, a)));
Function pointers are great fun.
Additionally, we can create array of pointers to function:
double fun0(double x, double y) {
return x + y;
}
double fun1(double x, double y) {
return x - y;
}
double fun2(double x, double y) {
return x / y;
}
int main(int argc, char*argv[]) {
const int MaxFunSize = 3;
double (*funPtr[MaxFunSize])(double, double) = { fun0, fun1, fun2 };
for(int i = 0; i < MaxFunSize; i++)
printf("%f\n", funPtr[i](2.5, 1.1));
return 0;
}
You can also define functions that return pointers to functions:
int (*f(int x))(double y);
f is a function that takes a single int parameter and returns a pointer to a function that takes a double parameter and returns int.