我试着搜索了很多,但我找不到我要找的东西。
例如:
struct A {
int something;
void(*function_ptr)(void);
function_ptr = function;
}
void function(void) {
struct A sth;
}
正如你所看到的,我不能在struct之前定义函数,因为它的结构体中包含了这个结构,但是当我在struct之前定义结构时,我不能指向那个函数,因为它还没有被声明。
您可能想要这样的内容:
#include <stdio.h>
struct A {
int something;
void(*function_ptr)(void);
};
void function(void) {
struct A sth;
// possibly use sth somewhere here
printf("Hello I'm in functionn");
}
int main()
{
struct A a;
a.function_ptr = function;
a.function_ptr();
}
或
int main()
{
struct A a = {0 , function }; // a.something = 0; a.function_ptr = function;
a.function_ptr();
}
或者甚至像这样:
struct A* NewstructA()
{
struct A* newstruct = malloc(sizeof(*newstruct));
newstruct->function_ptr = function;
}
int main()
{
struct A* a = NewstructA();
(a->function_ptr)();
}