问题描述
我有一个小问题。
我试图定义一个函数指针数组动态地释放calloc
。
但我不知道怎么写的语法。
非常感谢。
I've a little question.I'm trying to define an array of function pointers dynamically with calloc
. But I don't know how to write the syntax.Thanks a lot.
推荐答案
该类型的函数指针就像函数声明,但有(*)来代替函数名。这样的指针:
The type of a function pointer is just like the function declaration, but with "(*)" in place of the function name. So a pointer to:
int foo( int )
是:
int (*)( int )
为了来命名这种类型的实例,把名字里面(*),星之后,所以:
In order to name an instance of this type, put the name inside (*), after the star, so:
int (*foo_ptr)( int )
声明变量称为foo_ptr指向此类型的函数。
declares a variable called foo_ptr that points to a function of this type.
阵列跟着把括号中的变量标识符接近正常C语法,所以:
Arrays follow the normal C syntax of putting the brackets near the variable's identifier, so:
int (*foo_ptr_array[2])( int )
声明了一个名为foo_ptr_array变量,它是2函数指针数组。
declares a variable called foo_ptr_array which is an array of 2 function pointers.
语法可以得到pretty凌乱,所以它往往更容易做出的typedef函数指针,然后宣布这些不是数组:
The syntax can get pretty messy, so it's often easier to make a typedef to the function pointer and then declare an array of those instead:
typedef int (*foo_ptr_t)( int );
foo_ptr_t foo_ptr_array[2];
在任何样品你可以做这样的事情:
In either sample you can do things like:
int f1( int );
int f2( int );
foo_ptr_array[0] = f1;
foo_ptr_array[1] = f2;
foo_ptr_array[0]( 1 );
最后,您可以用动态的两种分配一个数组:
Finally, you can dynamically allocate an array with either of:
int (**a1)( int ) = calloc( 2, sizeof( int (*)( int ) ) );
foo_ptr_t * a2 = calloc( 2, sizeof( foo_ptr_t ) );
注意额外*第一行宣布A1作为一个指向函数指针。
Notice the extra * in the first line to declare a1 as a pointer to the function pointer.
这篇关于如何定义函数指针的C中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!