3

如何在 C 中创建“函数指针”(并且(例如)函数具有参数)?

4

5 回答 5

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; }
于 2009-08-14T16:32:05.360 回答
5
    typedef int (*funcptr)(int a, float b);

    funcptr x = some_func;

    int a = 3;
    float b = 4.3;
    x(a, b);
于 2009-08-14T16:34:33.903 回答
0

当我第一次深入研究函数指针时,我发现这个站点很有帮助。

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

于 2009-08-14T17:26:35.530 回答
0

首先声明一个函数指针:

typedef int (*Pfunct)(int x, int y);

几乎与函数原型相同。
但是现在您创建的只是一种函数指针(带有typedef)。
所以现在你创建了一个该类型的函数指针:

Pfunct myFunction;
Pfunct myFunction2;

现在为它们分配函数地址,您可以像使用函数一样使用它们:

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)));

函数指针非常有趣。

于 2009-08-14T17:44:32.577 回答
0

您还可以定义返回函数指针的函数:

int (*f(int x))(double y);

f 是一个函数,它接受单个 int 参数并返回一个指向函数的指针,该函数接受一个 double 参数并返回 int。

于 2009-08-14T20:11:29.003 回答