如何在C中定义函数数组 [英] How to define an array of functions in C
问题描述
我有一个包含如下声明的结构:
I have a struct that contains a declaration like this one:
void (*functions[256])(void) //Array of 256 functions without arguments and return value
在另一个函数中我想定义它,但是有 256 个函数!我可以这样做:
And in another function I want to define it, but there are 256 functions! I could do something like this:
struct.functions[0] = function0;
struct.functions[1] = function1;
struct.functions[2] = function2;
等等,但是这太累了,我的问题是有什么方法可以做这样的事情吗?
And so on, but this is too tiring, my question is there some way to do something like this?
struct.functions = { function0, function1, function2, function3, ..., };
编辑:如 Chris Lutz 所说,语法错误已更正.
EDIT: Syntax error corrected as said by Chris Lutz.
推荐答案
我有一个包含如下声明的结构:
I have a struct that contains a declaration like this one:
不,你没有.那是语法错误.您正在寻找:
No you don't. That's a syntax error. You're looking for:
void (*functions[256])();
这是一个函数指针数组.但是请注意,void func()
不是不带参数且不返回任何内容的函数".它是一个函数,它接受未指定的数字或类型的参数并且不返回任何内容.如果你想要没有参数",你需要这个:
Which is an array of function pointers. Note, however, that void func()
isn't a "function that takes no arguments and returns nothing." It is a function that takes unspecified numbers or types of arguments and returns nothing. If you want "no arguments" you need this:
void (*functions[256])(void);
在 C++ 中,void func()
确实 的意思是不带参数",这会引起一些混淆(尤其是因为 C 为 void func() 指定的功能)
的价值可疑.)
In C++, void func()
does mean "takes no arguments," which causes some confusion (especially since the functionality C specifies for void func()
is of dubious value.)
无论哪种方式,您都应该 typedef
您的函数指针.这将使代码更容易理解,并且您只有一次机会(在 typedef
处)弄错语法:
Either way, you should typedef
your function pointer. It'll make the code infinitely easier to understand, and you'll only have one chance (at the typedef
) to get the syntax wrong:
typedef void (*func_type)(void);
// ...
func_type functions[256];
反正你不能赋值给一个数组,但是你可以初始化一个数组并复制数据:
Anyway, you can't assign to an array, but you can initialize an array and copy the data:
static func_type functions[256] = { /* initializer */ };
memcpy(mystruct.functions, functions, sizeof(functions));
这篇关于如何在C中定义函数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!