小编典典

C 中的函数指针是如何工作的?

all

我最近对 ​​C 中的函数指针有了一些经验。

因此,继续回答您自己的问题的传统,我决定为那些需要快速深入了解该主题的人做一个非常基础的小总结。


阅读 112

收藏
2022-02-25

共1个答案

小编典典

C中的函数指针

让我们从一个我们将 指向 的基本函数开始:

int addInt(int n, int m) {
    return n+m;
}

首先,让我们定义一个指向函数的指针,该函数接收 2int并返回一个int

int (*functionPtr)(int,int);

现在我们可以安全地指向我们的函数:

functionPtr = &addInt;

现在我们有了一个指向函数的指针,让我们使用它:

int sum = (*functionPtr)(2, 3); // sum == 5

将指针传递给另一个函数基本上是一样的:

int add2to3(int (*functionPtr)(int, int)) {
    return (*functionPtr)(2, 3);
}

我们也可以在返回值中使用函数指针(尽量跟上,它会变得混乱):

// this is a function called functionFactory which receives parameter n
// and returns a pointer to another function which receives two ints
// and it returns another int
int (*functionFactory(int n))(int, int) {
    printf("Got parameter %d", n);
    int (*functionPtr)(int,int) = &addInt;
    return functionPtr;
}

但是使用 a 更好typedef

typedef int (*myFuncDef)(int, int);
// note that the typedef name is indeed myFuncDef

myFuncDef functionFactory(int n) {
    printf("Got parameter %d", n);
    myFuncDef functionPtr = &addInt;
    return functionPtr;
}
2022-02-25