I need to call a function using an integer. I'm really new to C language and the function pointer is horribly confusing.
Goal
- I have so many messy functions which will mess up all if I write them in the
main.c. - So I write those messy functions into another c file
messy_functs.c - In
main.c, I need to select one of those messy functions and call it, depending on the integer obtained from my algorithm. Those functions commonly needs two arguments,int inputandint *output. - The callee function will store the result in
outputwhich is passed as a pointer
My plan
- In
messy_functs.c, make an arrayfunction_list[]containing function pointers in the global scope. - In
messy_functs.c. Make a functionget_function_by_index(int function_index)that returns a function pointer indexed by the argument. - In
main.c, callmessy_functionpassingfunction_indexand then get the result by calling the returned function passing two argumentsint inputandint *output.
Problem
I made my code as follows. But failed with an error
error: too many arguments to function.. Please ignore some typos.
// main.c
#include "messy_functs.h"
...
void get_result(int func_idx, int input, int *output)
{
(*get_function_by_index(func_idx))(input, output);
}
int main() {
int result, data, func_idx;
...
func_idx, data = some_algorithm_i_made(~~);
get_result(func_idx, data, &result);
printf("Got the result %d\n", result);
}
============
// messy_functs.c
#define FUNCTION_NUM 100
const void (*function_list[FUNCITON_NUM])(int input, int *output) = {func1, func2, func3, func_m, func_qwer, func_abab, ...(many functions) };
void (*get_function_by_index(int func_id)){
return function_list[func_id];
}
void func1(int input, int *output) {...}
void func2(int input, int *output) {...}
(... other functions)
I've been tried to fix but got different errors such as void value not ignored as it ought to be.
I know there must be other good posts that can solve my problem. I've been read many posts about function pointers and array of function pointers but couldn't make it.