简体   繁体   English

C ADT函数指针作为参数?

[英]C ADT function pointer as parameter?

I have a function in an ADT: 我在ADT中有一个功能:

Pgroup new_group(int size, void (*foo)(void *));

In my other class I have this function to send in: 在我的另一堂课中,我有以下函数要发送:

void foo(Pstruc x);

x is a pointer to a struct. x是指向结构的指针。 When I try to call new_group however, I receive an error "expected 'void (*)(void )' but argument is of type 'void ( )(struct struc_ *)". 但是,当我尝试调用new_group时,出现错误“预期为'void(*)(void )',但参数类型为'void( )(struct struc_ *)”。 This is how I've been calling it: 我一直这样称呼它:

Pgroup group = new_group(num, &foo);

Any suggestions? 有什么建议么?

You can cast the argument to the correct type to get rid of the diagnostic: 您可以将参数转换为正确的类型以摆脱诊断:

Pgroup group = new_group(num, (void (*)(void *)) foo);

Note that this is not portable as C does not guarantee that the representation between different pointers is the same. 请注意,这不是可移植的,因为C不能保证不同指针之间的表示相同。 The best would be to use types that match in their declarations. 最好是使用与其声明中匹配的类型。

You can rewrite your original function from void foo(Pstruc x); 您可以从void foo(Pstruc x);重写原始函数void foo(Pstruc x); to void foo(void* x); 使void foo(void* x); .

Or convert its type: (void(*)(void*))foo . 或转换其类型: (void(*)(void*))foo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM