如何在 C 中定义函数指针数组 [英] How define an array of function pointers in C

查看:31
本文介绍了如何在 C 中定义函数指针数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小问题.我正在尝试使用 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.

语法可能会变得非常混乱,因此通常更容易为函数指针创建一个 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 中定义函数指针数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆