问题描述
我要创建执行由参数的一组数据传递的函数的函数。你如何将一个函数在C参数?
I want to create a function that performs a function passed by parameter on a set of data. How do you pass a function as a parameter in C?
推荐答案
声明
一个一个函数原型,它接受一个函数参数如下所示:
A prototype for a function which takes a function parameter looks like the following:
void func ( void (*f)(int) );
这指出参数˚F
将是一个指针,它有一个无效
返回类型和函数只需要一个 INT
参数。下面的函数(打印
)是可以传递给 FUNC
作为参数的函数的例子,因为它是正确的类型:
This states that the parameter f
will be a pointer to a function which has a void
return type and which takes a single int
parameter. The following function (print
) is an example of a function which could be passed to func
as a parameter because it is the proper type:
void print ( int x ) {
printf("%d\n", x);
}
函数调用
当调用带有函数参数的函数,传递的值必须是指向一个功能。用于这种用途的函数名(没有括号):
When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this:
func(print);
会叫 FUNC
,传递打印功能吧。
函数体
与任何参数,FUNC现在可以使用的参数的名称在函数体访问参数的值。让我们说,FUNC将应用它被传递给数0-4的功能。首先考虑哪些循环会是什么样子直接调用打印:
As with any parameter, func can now use the parameter's name in the function body to access the value of the parameter. Let's say that func will apply the function it is passed to the numbers 0-4. Consider, first, what the loop would look like to call print directly:
for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
print(ctr);
}
由于 FUNC
的参数声明说,˚F
是一个指向所需功能的名字,我们记得第一次,如果˚F
是一个指针,那么 *˚F
是的东西˚F
点(即功能打印
在这种情况下)。这样一来,只需更换打印的每一个发生在环以上 *˚F
:
Since func
's parameter declaration says that f
is the name for a pointer to the desired function, we recall first that if f
is a pointer then *f
is the thing that f
points to (i.e. the function print
in this case). As a result, just replace every occurrence of print in the loop above with *f
:
void func ( void (*f)(int) ) {
for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
(*f)(ctr);
}
}
从http://math.hws.edu/bridgeman/courses/331/f05/handouts/c-c++-notes.html
这篇关于你如何将一个函数在C参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!