C - 奇怪的原型论证
这个函数原型发生了什么?显然,带有某种类型转换的 void 参数令人困惑......
int *my_func(my_struct *m, void (*m_op)(my_struct *v, void arg));
What's going on in this function prototype? Obviously the void parameter with some sort of typecasting is confusing...
int *my_func(my_struct *m, void (*m_op)(my_struct *v, void arg));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
函数
my_func
的第二个参数是一个指向函数的指针,该函数不返回任何值 (void
),但它接受两个参数,一个my_struct
指针和...和(无效的)void
。后者可能应该是void *arg
;您不能拥有void
类型的变量或参数。按照目前的情况,代码不应该编译。The second argument to the function
my_func
is a pointer to a function that returns no value (void
), but which takes two arguments, amy_struct
pointer and ... and (an invalid)void
. The latter should probably bevoid *arg
; you cannot have a variable or argument of typevoid
. As it stands, the code should not compile.此原型声明了一个返回
int *
的函数my_func
。它有两个参数,第一个是my_struct *
类型,第二个是奇怪的类型void (*)(my_struct *, void)
。这意味着第二个参数是一个指向返回 void 的函数的指针,它本身有两个参数,一个指向 my_struct 和 void 的指针(我认为这是一个拼写错误,它接受一个void *
)。This prototype declares a function,
my_func
that returnsint *
. It takes two arguments, the first being of typemy_struct *
and the second of the strange typevoid (*)(my_struct *, void)
. This means that the second argument is a pointer to a function that returns void and takes 2 arguments itself, a pointer tomy_struct
andvoid
(I assume that was a typo and it takes avoid *
).这篇小文章解释了如何以螺旋状的方式解析 C 声明。构建过程是相反的。
This little article explains how to parse C declarations in a spiral-like motion. Constructing is done in the reverse.
我的建议 - 始终尝试将声明拆分为较小的声明 - 在这种情况下代码将更具可读性。在这种情况下,您可以将代码重写为:
正如大家所说 - 关于 m_op_function 的第二个参数,这里几乎有 99,99% 的拼写错误 - 可能是
void*
- 这样您就可以传递任何指针到它 - 无论是(char*)、(int*)、(my_struct*)
或其他任何内容。只需投射指针即可。My suggestion - always try to split declarations into smaller ones - in that case code will be more readable. In this case you could re-write code as:
And as everybody said- it's almost 99,99% typo here regarding second parameter to m_op_function- it is possible
void*
- so that you can pass any pointer to it - be it(char*), (int*), (my_struct*)
, or anything else. Simply just cast pointer.