C 中的函数指针是如何工作的? [英] How do function pointers in C work?

查看:21
本文介绍了C 中的函数指针是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I had some experience lately with function pointers in C.

因此,按照自己回答问题的传统,我决定对基础知识做一个小总结,供那些需要快速深入了解该主题的人使用.

So going on with the tradition of answering your own questions, I decided to make a small summary of the very basics, for those who need a quick dive-in to the subject.

推荐答案

C中的函数指针

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

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

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

First thing, let's define a pointer to a function which receives 2 ints and returns an int:

int (*functionPtr)(int,int);

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

Now we can safely point to our function:

functionPtr = &addInt;

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

Now that we have a pointer to the function, let's use it:

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

将指针传递给另一个函数基本相同:

Passing the pointer to another function is basically the same:

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

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

We can use function pointers in return values as well (try to keep up, it gets messy):

// 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 中的函数指针是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆