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

查看:88
本文介绍了如何函数指针用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.

推荐答案

让我们先从基本的功能,我们会的指向的:

Functions pointers in C

Let's start with a basic function which we will be pointing to:

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

第一件事情,让我们定义一个指针接收2 INT 和回报和 INT 功能:

int (*functionPtr)(int,int);

现在我们可以放心地指向我们的功能:

Now we can safely point to our function:

functionPtr = &addInt;

现在,我们有一个指针功能,让使用它:

Now that we have a pointer to the function, lets 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天全站免登陆