C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了C中的函数指针如何工作?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我最近在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中的函数指针如何工作?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。