views:

423

answers:

7

How can I create a "function pointer" (and (for example) the function has parameters) in C?

+13  A: 

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
Interesting example - *adding* a float and two chars?
Graeme Perrow
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
+7  A: 

This previous SO question may help you:

http://stackoverflow.com/questions/840501/how-do-function-pointers-in-c-work

Amber
+5  A: 
    typedef int (*funcptr)(int a, float b);

    funcptr x = some_func;

    int a = 3;
    float b = 4.3;
    x(a, b);
xcramps
A: 

I found this site helpful when I was first diving into function pointers.

http://www.newty.de/fpt/index.html

Rob Jones
A: 

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
A: 

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;
}
mykhaylo
A: 

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