vimer linux kernel 爱好者

回调函数的使用方法

2016-05-20

[来自](http://stackoverflow.com/questions/142789/what-is-a-callback-in-c-and-how-are-they-implemented)

这里没有回调在c中,这里使用函数指针实现,举个例子:


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);
    ...
}
Here, the populate_array function takes a function pointer as its third parameter, and calls it to get the values to populate the array with. We've written the callback getNextRandomValue, which returns a random-ish value, and passed a pointer to it to populate_array. populate_array will call our callback function 10 times and assign the returned values to the elements in the given array.

上一篇 sort排序

Comments

Content