【发布时间】:2011-07-26 04:58:29
【问题描述】:
我有一个小问题。
我正在尝试使用calloc 动态定义函数指针数组。
但我不知道如何编写语法。
非常感谢。
【问题讨论】:
-
你能告诉我们你到目前为止写的东西吗?
标签: c++ c arrays function-pointers
我有一个小问题。
我正在尝试使用calloc 动态定义函数指针数组。
但我不知道如何编写语法。
非常感谢。
【问题讨论】:
标签: c++ c arrays function-pointers
假设你所有的函数都是void ()(void)类型的,像这样
typedef void (*fxptr)(void);
fxptr *ptr; // pointer to function pointer
ptr = malloc(100 * sizeof *ptr);
if (ptr) {
ptr[0] = fx0;
ptr[1] = fx1;
/* ... */
ptr[99] = fx100;
/* use "dynamic array" of function pointers */
free(ptr);
}
【讨论】:
typedef R (*fptr)(A1, A2... An);
其中 R 是返回类型,A1、A2... An 是参数类型。
fptr* arr = calloc(num_of_elements,sizeof(fptr));
【讨论】:
函数指针的类型和函数声明一样,只是用“(*)”代替函数名。所以一个指向:
int foo( int )
应该是:
int (*)( int )
为了命名这种类型的实例,请将名称放在 (*) 内,在星号之后,所以:
int (*foo_ptr)( int )
声明一个名为 foo_ptr 的变量,该变量指向该类型的函数。
数组遵循将括号放在变量标识符附近的正常 C 语法,因此:
int (*foo_ptr_array[2])( int )
声明一个名为 foo_ptr_array 的变量,它是一个由 2 个函数指针组成的数组。
语法可能会变得非常混乱,因此通常更容易为函数指针创建 typedef 然后声明它们的数组:
typedef int (*foo_ptr_t)( int );
foo_ptr_t foo_ptr_array[2];
在任一示例中,您都可以执行以下操作:
int f1( int );
int f2( int );
foo_ptr_array[0] = f1;
foo_ptr_array[1] = f2;
foo_ptr_array[0]( 1 );
最后,您可以使用以下任一方式动态分配数组:
int (**a1)( int ) = calloc( 2, sizeof( int (*)( int ) ) );
foo_ptr_t * a2 = calloc( 2, sizeof( foo_ptr_t ) );
注意第一行中额外的 * 将 a1 声明为指向函数指针的指针。
【讨论】:
calloc 结果怎么样?没有必要吗?例如:int (**a1)( int ) = (some_casting) calloc( 2, sizeof( int (*)( int ) ) );
void * 类型将隐式转换为任何其他指向对象的指针类型。
我在这里放了一个小例子,可能对你有帮助
typedef void (*fp)(int); //Declares a type of a void function that accepts an int
void test(int i)
{
printf("%d", i);
}
int _tmain(int argc, _TCHAR* argv[])
{
fp function_array[10]; //declares the array
function_array[0] = test; //assings a function that implements that signature in the first position
function_array[0](10); //call the cuntion passing 10
}
【讨论】:
您可以将函数指针数组声明为
T (*afp[N])();
对于某些类型T。由于您正在动态分配数组,因此您会执行类似的操作
T (**pfp)() = calloc(num_elements, sizeof *pfp);
或
T (**pfp)() = malloc(num_elements * sizeof *pfp);
然后您将每个函数调用为
T x = (*pfp[i])();
或
T x = pfp[i](); // pfp[i] is implicitly dereferenced
如果你想不正统,你可以声明一个指向函数指针数组的指针,然后按如下方式分配它:
T (*(*pafp)[N])() = malloc(sizeof *pafp);
虽然您在调用时必须遵守数组指针:
x = (*(*pafp)[i])();
【讨论】: