Generic function pointers in C
- by Lucas
I have a function which takes a block of data and the size of the block and a function pointer as argument. Then it iterates over the data and performes a calculation on each element of the data block.
The following is the essential outline of what I am doing:
int myfunction(int* data, int size, int (*functionAsPointer)(int)){
//walking through the data and calculating something
for (int n = 0; n < size; n++){
data[n] = (*function)(data[n]);
}
}
The functions I am passing as arguments look something like this:
int mycalculation(int input){
//doing some math with input
//...
return input;
}
This is working well, but now I need to pass an additional variable to my functionpointer. Something along the lines
int mynewcalculation(int input, int someVariable){
//e.g.
input = input * someVariable;
//...
return input;
}
Is there an elegant way to achieve this and at the same time keeping my overall design idea?