0

Possible Duplicate:
How do function pointers in C work?

Surfing on stackoverflow I found this example:

/* Validation functions start */
void populate_array(int *array, size_t arraySize, int (*getNextValue)(void))
{
    for (size_t i=0; i<arraySize; i++)
        array[i] = getNextValue();
}

int getNextRandomValue(void)
{
    return rand();
}

int main(void)
{
    int myarray[10];
    populate_array(myarray, 10, getNextRandomValue);
    ...
}

I was wondering, imagine getNextRandomValue had a parameter getNextRandomValue(int i), how would I include this and making the function accepting inputs?

Many thanks

Community
  • 1
  • 1
piggyback
  • 9,034
  • 13
  • 51
  • 80

3 Answers3

4

Common practice is to pass a pointer to "data" together with the function. When function gets called, pass that "data" pointer into function and assume that the function itself knows what to do with that data. In fact the data is usually a pointer to a structure. So the code looks like this:

struct func1_data {
    int a;
    int b;
};

struct func2_data {
    char x[10];
};

int function1(void *data) {
    struct func1_data *my_data = (typeof(my_data)) data;
    /* do something with my_data->a and my_data->b */
    return result;
}

int function2(void *data) {
    struct func2_data *my_data = (typeof(my_data)) data;
    /* do something with my_data->x */
    return result;
}

and assume we have

int caller(int (*callback), void *data) {
    return callback(data);
}

Then you call all this like this:

struct func1_data data1 = { 5, 7 };
struct func2_data data2 = { "hello!" };
caller(function1, (void *) &data1);
caller(function2, (void *) &data2);
aragaer
  • 17,238
  • 6
  • 47
  • 49
2

It's probably a good idea to get familiar with function-pointer syntax. You need to change the argument to int (*getNextValue)(int).

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
2

Then your code should be like this...

void populate_array(int *array, size_t arraySize, int (*getNextValue)(unsigned int))
{
    unsigned int seedvalue = 100;

    for (size_t i=0; i<arraySize; i++)
        array[i] = getNextValue(seedvalue);
}

int getNextRandomValue(unsigned int seed)
{
    srand(seed);
    return rand();
}

int main(void)
{
    int myarray[10];
    populate_array(myarray, 10, getNextRandomValue);
    ...
}
Adeel Ahmed
  • 1,591
  • 8
  • 10