APo*_*Dev 2 c pointers structure
嘿家伙我有一个问题:如何从带有指针的枚举结构中调用函数?
例如,我有这样的结构:
typedef enum struct_e
{
FUNCTION_ONE,
FUNCTION_TWO,
FUNCTION_THREE,
FUNCTION_FOUR,
} sctruct_t;
Run Code Online (Sandbox Code Playgroud)
我有一个函数接收这些变量之一和函数的参数(例如int)
void call_functions(struct_t action, int exemple) {...}
// -> call like this call_functions(FUNCTION_ONE, 45);
Run Code Online (Sandbox Code Playgroud)
在该函数中,我必须调用以下函数之一:
void function_one(int a)
{
printf("You have %d years old", a);
}
Run Code Online (Sandbox Code Playgroud)
假设要调用的每个函数都有类型void (*)(int),您可以使用枚举值作为数组索引来创建函数指针数组:
typedef void (*call_func_type)(int);
call_func_type func_list[] = {
[FUNCTION_ONE] = function_one,
[FUNCTION_TWO] = function_two,
[FUNCTION_THREE] = function_three,
[FUNCTION_FOUR] = function_four
}
Run Code Online (Sandbox Code Playgroud)
然后call_functions只是索引到该数组:
void call_functions(struct_t action, int example)
{
func_list[action](example);
}
Run Code Online (Sandbox Code Playgroud)