How can I create a "function pointer" (and (for example) the function has parameters) in C?
Asked
Active
Viewed 1,367 times
3
-
possible duplicate of [How do function pointers in C work?](http://stackoverflow.com/questions/840501/how-do-function-pointers-in-c-work) – Peter Smit Sep 09 '12 at 11:26
5 Answers
15
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; }

John Millikin
- 197,344
- 39
- 212
- 226
-
-
Of course, haven't you always wanted to add 3.145 to 'z' and return the result as an integer!? I'll change the example to something a bit saner. – John Millikin Aug 14 '09 at 16:45
5
typedef int (*funcptr)(int a, float b);
funcptr x = some_func;
int a = 3;
float b = 4.3;
x(a, b);

xcramps
- 1,203
- 1
- 9
- 9
0
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.

Carson Myers
- 37,678
- 39
- 126
- 176
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.

John Bode
- 119,563
- 19
- 122
- 198