大佬教程收集整理的这篇文章主要介绍了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中的函数指针如何工作?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。