[英]pointer to function, struct as parameter
今天又重新打字了。。
在结构中是指向 function 的指针,在这个 function 中,我希望能够处理来自这个结构的数据,所以指向结构的指针作为参数给出。
这个问题的演示
#include <stdio.h>
#include <stdlib.h>
struct tMYSTRUCTURE;
typedef struct{
int myint;
void (* pCallback)(struct tMYSTRUCTURE *mystructure);
}tMYSTRUCTURE;
void hello(struct tMYSTRUCTURE *mystructure){
puts("!!!Hello World!!!"); /* prints !!!Hello World!!! */
}
int main(void) {
tMYSTRUCTURE mystruct;
mystruct.pCallback = hello;
mystruct.pCallback(&mystruct);
return EXIT_SUCCESS;
}
但我收到警告
..\src\retyping.c:31:5:警告:从不兼容的指针类型传递 'mystruct.pCallback' 的参数 1..\src\retyping.c:31:5:'注意:预期'MYSTRUCTURE参数的类型为“struct tMYSTRUCTURE *”
预期 'struct tMYSTRUCTURE *' 但是 'struct tMYSTRUCTURE *',很有趣!
任何想法如何解决它?
问题是由typedef
结构然后使用struct
关键字和typedef
的名称引起的。 前向声明struct
和typedef
可以解决问题。
#include <stdio.h>
#include <stdlib.h>
struct tagMYSTRUCTURE;
typedef struct tagMYSTRUCTURE tMYSTRUCTURE;
struct tagMYSTRUCTURE {
int myint;
void (* pCallback)(tMYSTRUCTURE *mystructure);
};
void hello(tMYSTRUCTURE *mystructure){
puts("!!!Hello World!!!"); /* prints !!!Hello World!!! */
}
int main(void) {
tMYSTRUCTURE mystruct;
mystruct.pCallback = hello;
mystruct.pCallback(&mystruct);
return EXIT_SUCCESS;
}
更正的代码:
#include <stdio.h>
#include <stdlib.h>
struct tMYSTRUCTURE_;
typedef struct tMYSTRUCTURE_ {
int myint;
void (* pCallback)(struct tMYSTRUCTURE_ *mystructure);
} tMYSTRUCTURE;
void hello(tMYSTRUCTURE *mystructure){
puts("!!!Hello World!!!"); /* prints !!!Hello World!!! */
}
int main(void) {
tMYSTRUCTURE mystruct;
mystruct.pCallback = hello;
mystruct.pCallback(&mystruct);
return EXIT_SUCCESS;
}
请注意struct
名称和typedef
名称之间的区别。 是的,您可以使它们相同,但是许多人(包括我自己)发现这令人困惑……通常的做法是使它们保持不同。
诚然,GCC 在这里的诊断有点奇怪。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.