int *(*(*functions_array)[4]();
int *function() { /*code */ };
我知道有一个引用函数int *(*func)();
的指针,我可以将函数的指针值赋给func func = &function;
,然后用func();
调用。
什么是最接近这种行为,但增加了数组?
你可能想要这个:
#include <stdio.h>
int function1(void)
{
printf("function 1\n");
return 1;
};
int function2(void)
{
printf("function 2\n");
return 2;
};
int(*FunctionPointer)(void); // a function pointer
int(*ArrayOfFunctionPointers[4])(void); // an array of 4 function pointers
int main()
{
FunctionPointer = function1;
FunctionPointer(); // will call function1
FunctionPointer = function2;
FunctionPointer(); // will call function2
ArrayOfFunctionPointers[0] = function1;
ArrayOfFunctionPointers[1] = function2;
for (int i = 0; i < 2; i++)
{
ArrayOfFunctionPointers[i]();
}
}
输出:
function 1
function 2
function 1
function 2
首先,你展示的宣言是不正确的。毫不奇怪,考虑到C中的声明符语法有多难。如果你想要一个函数指针数组(我强烈怀疑的话),那么原始拼写是这样的:
int *(*functions_array[4])();
没有更多的可读性,但至少在语法上是正确的。您现在可以索引它以获取供您使用的函数指针。例如:
functions_array[0] = function;
functions_array[0](); // Call the function
但是如果你真的想要一个指向数组的指针(由于我无法理解的原因),原始声明符是这样的:
int *(*(*functions_array_p)[4])();
使用现在不太吸引人的索引来匹配:
(*functions_array_p)[0] = function;
(*functions_array_p)[0](); // Call the function
由于*
和[]
的常规优先级,所以括号是必需的。
但是,使用它并更容易定义它的方法是引入一些类型别名。主要是针对函数类型:
typedef int* function_type();
现在,数组声明采用了这种更易读的形式:
function_type* functions_array[4];
普通视线中的星号与不隐藏指针语义的一般良好做法是一致的。
对于指向数组的指针:
function_type* (*functions_array)[4];
声明者看起来仍然很规律。
1.另外,C函数声明中的空参数列表并不意味着该函数不带参数。这是一个过时的功能,提供没有原型的功能。前进的方向是(void)
。