I am using C and looking to populate an array with pointers to various functions. I would like to use a function to pass the address of the function I want to put in the array. This is what I am trying to do with no success. The compiler is barking at my "task *ptr" deceleration in the prototype and registerTask function definition. I see a lot of examples of arrays with pointers to functions but none that first pass the address of the function through a function argument and then update the array. Any suggestions welcome.
typedef void (*task)(void);
task TaskArray[32];
// Prototypes
void taskA(void);
void taskB(void);
void registerTask(task *ptr);
// This is the problem function definition
void registerTask(task *ptr) {
TaskArray[TaskIndex] = ptr;
++TaskIndex;
}
// Some example functions definitions
void taskA(void) { }
void taskB(void) { }
int TaskIndex = 0;
main {
registerTask(&taskA); // place taskA pointer in array
registerTask(&taskB); // place taskB pointer in array
...later on...
TaskIndex = value; // Set the Task Array function Index
(*TaskArray[TaskIndex]); // call the function
}
(*function_ptr)(args);notation for calling a function via a pointer to function. But the second set of parentheses is necessary, with arguments if the function takes them (yourtaskfunctions don't, of course). Your compiler should be warning you about a statement with no effect -- if it isn't, you need to turn up the warning level until it does (gcc -Wallis probably sufficient; I'd recommendgcc -Wall -Wextra, though I use even more stringent options for my own code).