如何定义函数C中的数组 [英] How to define an array of functions in C
问题描述
我有一个包含这样一个声明中的结构:
无效(*功能[256])(无效)// 256阵列功能,不带任何参数和返回值
和在另一个函数我想定义它,但也有256的功能!
我可以做这样的事情:
struct.functions [0] = function0;
struct.functions [1] =功能1;
struct.functions [2] =函数2;
等等,但这是太累了,我的问题是有一些方法可以做这样的事情?
struct.functions = {function0,功能1,功能2,function3,...};
修改:语法错误由克里斯·卢茨说更正
。
我有一个包含这样一个声明中的结构:
块引用>没有你不知道。这是一个语法错误。您正在寻找:
无效(*功能[256])();
这是一个函数指针数组。但是请注意,该
无效FUNC()
不是的功能,它没有参数和返回任何结果。这是一个函数,它未指定号码或类型的参数,并且没有返回。如果你想不争论,你需要这样的:无效(*功能[256])(无效);
在C ++中,
无效FUNC()
的不的意思是不带任何参数,这会导致一些混乱(特别是因为功能Ç指定无效FUNC()
是可疑的价值。)无论哪种方式,你应该
的typedef
您的函数指针。这将使得code无限更容易理解,而你只有一次机会(在的typedef
),以获得语法错误的:无效的typedef(* func_type)(无效);
// ...
func_type函数[256];无论如何,你不能分配到一个数组,但你可以初始化数组和复制数据:
静态func_type功能[256] = {/ *初始化* /};
的memcpy(struct.functions,函数的sizeof(功能));I have a struct that contains a declaration like this one:
void (*functions[256])(void) //Array of 256 functions without arguments and return value
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, ..., };
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])();
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);
In C++,
void func()
does mean "takes no arguments," which causes some confusion (especially since the functionality C specifies forvoid func()
is of dubious value.)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 thetypedef
) 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(struct.functions, functions, sizeof(functions));
这篇关于如何定义函数C中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!