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

标签 c function-pointers

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

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

最佳答案

C 中的函数指针

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

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

首先,让我们定义一个指向函数的指针,该函数接收 2 个 int 并返回一个 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;
}

但是使用 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;
}

关于c - C 中的函数指针是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/840501/

相关文章:

c - GTK+ 将字体更改为旋转按钮

c - EOF是否设置了errno?

c++ - 如何将成员函数作为回调参数传递给需要 `typedef-ed` 自由函数指针的函数?

c++ - 预先定义可变参数函数指针参数

c - C 中的匿名 union

c - 线程之间是否可以通过LINX进行通信?

c - pthread_cond_t 条件下的 volatile 变量

C 函数指针 : Can I jump to heap memory assembler code?

C - 向函数传递一个指向函数指针的指针

c++ - C++ 中的成员函数指针