Generic function pointers in C

Posted by Lucas on Stack Overflow See other posts from Stack Overflow or by Lucas
Published on 2010-03-16T19:37:56Z Indexed on 2010/03/16 19:41 UTC
Read the original article Hit count: 415

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about c

    Related posts about abstraction