函数指针作为参数
是否可以将函数指针作为参数传递给 C 中的函数?
如果是这样,我将如何声明和定义一个以函数指针作为参数的函数?
Is it possible to pass a function pointer as an argument to a function in C?
If so, how would I declare and define a function which takes a function pointer as an argument?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
确实。
Definitely.
假设您有一个函数:
那么指向它的指针将是:
然后,您可以像这样使用它:
为了避免每次需要时都指定完整的指针类型,您可以
typedef
它:并且然后像使用任何其他类型一样使用它:
我建议查看世界著名的 C 常见问题解答。
Let's say that you have a function:
So the pointer to it will be:
Then, you could use it like this:
To avoid specifying the full pointer type every time you need it you coud
typedef
it:And then use it like any other type:
I suggest looking at the world-famous C faqs.
这是一个很好的例子:
This is a good example :
正如其他答案所述,您可以这样做,
但是,声明函数指针类型的参数有一种特殊情况:如果参数具有函数类型,它将被转换为指向函数类型的指针,就像数组会转换为参数列表中的指针,因此前者也可以写为
当然,这仅适用于参数,如在参数列表之外
int compar(const void *, const void *);
会声明一个函数。As said by other answers, you can do it as in
However, there is one special case for declaring an argument of function pointer type: if an argument has the function type, it will be converted to a pointer to the function type, just like arrays are converted to pointers in parameter lists, so the former can also be written as
Naturally this applies to only parameters, as outside a parameter list
int compar(const void *, const void *);
would declare a function.检查qsort()
函数的最后一个参数是函数指针。当您在自己的程序中调用
qsort()
时,执行会通过使用该指针“进入库”并“退回到您自己的代码”。Check
qsort()
The last argument to the function is a function pointer. When you call
qsort()
in a program of yours, the execution "goes into the library" and "steps back into your own code" through the use of that pointer.