如何将 typedef 用于函数指针数组

How to use typedef to an array of function pointers

我有一个函数指针数组:

int (*collection[2]) (int input1, int input 2) = {&fct1,&fct2}

我可以通过调用数组中的两个函数来获取值:

*collection[0](1,2);
*collection[1](1,2);

使用typedef,我想要另一种调用函数指针数组的方法。到目前为止,我正在做:

typedef int (*alternameName)(int input1, int input 2);
alternateName p = &collection[2];
int result1 = (*p[0])(1,2);
int result2 = (*p[1])(1,2);
printf("results are: %d, %d",result1, result2);

我的问题是我认为我没有正确定义变量 p,因为我的结果一直是 0。

typedef 函数类型通常比函数指针更清晰。它导致更清晰的语法:

typedef int collection_f(int, int);

现在您可以将 collection 定义为指向 collection_f.

的指针数组
collection_f* collection[2] = {&fct1,&fct2};

典型的调用语法是:

collection[0](1,2);
collection[1](1,2);

调用前不要de-reference函数指针。实际上,调用运算符将​​ 函数指针 作为操作数,而不是函数。函数在所有上下文中衰减为函数指针,除了 & 运算符 ... returns 一个函数指针。

接下来,我不确定是什么:

alternateName p = &collection[2];

应该是这个意思。我假设您希望 p 指向 collection 的第一个元素。此外,索引 p[1]p[2] 看起来像是越界访问,因为访问集合仅针对索引 0 和 1 定义。

现在您的代码可以重写了:

collection_f** p = collection; // pointer to first element which is a pointer to collection_f
int result1 = p[0](1,2);
int result2 = p[1](1,2);
printf("results are: %d, %d",result1, result2);

我希望它能解决问题。