2014-09-24 157 views
0

是否有可能创建一个指向函数指针,即指向函数指针

int32_t (*fp[2])(void) = {test_function1, test_function_2}; // initialize a function pointer 

<unknown> = fp; 

需要什么代替未知写? “正常”阵列,我可以这样做:

int a[2] = {0, 1}; 

int* p = a; 

非常感谢提前。

+0

你为什么声明'fp'作为函数指针数组,如果你只想要一个单一的指针? – 2014-09-24 09:34:47

+0

至于你的问题,你需要声明一个变量,它是指向函数指针数组的*指针,指向数组的*指针是这里的重要部分。如果那不是你想要的,那么除非你告诉我们你想要什么,否则我们无法帮助你。可能*为什么*你想要它(阅读[XY问题](http://meta.stackoverflow.com/questions/66377/what-is-the-xy-problem))。 – 2014-09-24 09:36:05

+0

函数指针数组的大小应该是不相关的。 – user2389717 2014-09-24 09:37:16

回答

12
typedef void(*func_ptr_t)(void); // a function pointer 

func_ptr_t* ptr_to_func_ptr;  // a pointer to a function pointer - easy to read 
func_ptr_t arr[2];    // an array of function pointers - easy to read 

void(**func_ptr_ptr)(void);  // a pointer to a function pointer - hard to read 
void(*func_ptr_arr [2])(void); // an array of function pointers - hard to read 
+0

如果我有void(** foo)(int,int)作为指向函数指针的指针。如何使用函数指针? – Bionix1441 2016-08-24 14:18:22

+1

http://stackoverflow.com/questions/36564473/pointer-to-a-function-a-different-approach-of-declaring – 2016-10-28 10:05:11

2
typedef int32_t FP(void); 

FP *fp[2] = { test_function1, test_function2 }; 
FP **p = fp; 
+0

就我个人而言,我可能会将类型别名“FP”作为指针,但这只是个人品味的问题。 :) – 2014-09-24 09:47:43

+1

@JoachimPileborg我也会这样做,函数指针是唯一可以将指针隐藏在typedef后面的情况。但我认为这个答案中的风格也很好,因为它符合永不typedef的规则:删除一个指针。 – Lundin 2014-09-24 09:50:08

+0

这样你也可以声明函数,例如'FP test_function1,test_function2;' – 2014-09-24 09:51:01