最近我对 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/