C 如何在结构中声明函数指针,指针指向的函数在其主体中包含该结构?

C 如何在结构中声明函数指针,指针指向的函数在其主体中包含该结构?,c,struct,C,Struct,我试着搜索了很多,但我找不到我要找的东西 例如: 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);
 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 function\n");
}

int main()
{
  struct A a;
  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)();
}
甚至像这样:

#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 function\n");
}

int main()
{
  struct A a;
  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)();
}

sth.function\u ptr=function
inside
function
是否符合您的要求?您不能在结构定义中有赋值。您可能需要这样的东西:
structasth={42,function}函数的声明是可见的。我可以这样做,但我仍然需要在结构A中表示该函数的东西。好的,您可以使用前向声明(参见示例),但对我来说,这似乎是一个问题。那么我如何在我的结构A中指出该函数。谢谢,我可以利用它,但我计划对很多结构进行malloc,所以我不想在那之后初始化它们,也许我可以用extern做我想做的事情。写一个函数来做malloc和初始化,如果我做不到的话,我会这么做simpler@namenamename问题编辑