Possible Duplicate:
How do function pointers in C work?
在 stackoverflow 上冲浪我找到了这个例子:
/* 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);
...
}
我想知道,假设 getNextRandomValue 有一个参数 getNextRandomValue(int i),我将如何包含它并使函数接受输入?
非常感谢
通常的做法是将指向“数据”的指针与函数一起传递。当函数被调用时,将该“数据”指针传递给函数并假设函数本身知道如何处理该数据。实际上,数据通常是指向结构的指针。所以代码看起来像这样:
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;
}
假设我们有
int caller(int (*callback), void *data) {
return callback(data);
}
然后你这样调用所有这些:
struct func1_data data1 = { 5, 7 };
struct func2_data data2 = { "hello!" };
caller(function1, (void *) &data1);
caller(function2, (void *) &data2);