0x7*_*77D 16 c arrays function definition
我有一个包含这样的声明的结构:
void (*functions[256])(void) //Array of 256 functions without arguments and return value
Run Code Online (Sandbox Code Playgroud)
在另一个函数我想定义它,但有256个函数!我可以这样做:
struct.functions[0] = function0;
struct.functions[1] = function1;
struct.functions[2] = function2;
Run Code Online (Sandbox Code Playgroud)
等等,但这太累了,我的问题是有办法做这样的事吗?
struct.functions = { function0, function1, function2, function3, ..., };
Run Code Online (Sandbox Code Playgroud)
编辑:Chris Lutz所说的修正了语法错误.
Chr*_*utz 19
我有一个包含这样的声明的结构:
不,你没有.这是一个语法错误.您正在寻找:
void (*functions[256])();
Run Code Online (Sandbox Code Playgroud)
哪个是函数指针数组.但请注意,这void func()
不是"不带参数且不返回任何内容的函数".它是一个函数,它接受未指定的数字或类型的参数,并且不返回任何内容.如果你想要"没有参数",你需要这个:
void (*functions[256])(void);
Run Code Online (Sandbox Code Playgroud)
在C++中,void func()
确实是指"不带任何参数",这会导致一些混乱(特别是因为功能Ç指定void func()
是可疑值的).
无论哪种方式,你应该是typedef
你的函数指针.它将使代码更容易理解,并且你只有一次机会(在typedef
)获得语法错误:
typedef void (*func_type)(void);
// ...
func_type functions[256];
Run Code Online (Sandbox Code Playgroud)
无论如何,您无法分配给数组,但您可以初始化数组并复制数据:
static func_type functions[256] = { /* initializer */ };
memcpy(struct.functions, functions, sizeof(functions));
Run Code Online (Sandbox Code Playgroud)
Swe*_*gin 10
我有同样的问题,这是我测试解决方案的小程序。它看起来很简单,所以我想我会为未来的访客分享它。
#include <stdio.h>
int add(int a, int b) {
return a+b;
}
int minus(int a, int b) {
return a-b;
}
int multiply(int a, int b) {
return a*b;
}
typedef int (*f)(int, int); //declare typdef
f func[3] = {&add, &minus, &multiply}; //make array func of type f,
//the pointer to a function
int main() {
int i;
for (i = 0; i < 3; ++i) printf("%d\n", func[i](5, 4));
return 0;
}
Run Code Online (Sandbox Code Playgroud)