[英]How define an array of function pointers in C
我有一个小问题。 我正在尝试使用calloc
动态定义一个函数指针数组。 但我不知道如何编写语法。 非常感谢。
函数指针的类型就像函数声明一样,只是用“(*)”代替了函数名。 所以指向:
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 声明为指向函数指针的指针。
我在这里放了一个小例子,可能对你有帮助
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])();
假设你所有的函数都是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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.