如何在 c 工作中使用函数指针? | 您所在的位置:网站首页 › 函数指针的用法 › 如何在 c 工作中使用函数指针? |
Function 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; }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 == 5Passing 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; }But it's much nicer to use a 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; } |
今日新闻 |
推荐新闻 |
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 |