C:将函数指针放在函数使用该结构作为参数的结构中

Mid*_*ver 3 c struct function-pointers function

我好像遇到了鸡和蛋的问题.

我希望有一个结构,作为其成员之一是一个函数指针.但是这个函数指针想要使用与它的参数相同的结构.这会产生一个问题,我必须先定义函数指针才能将其作为成员包含,但在定义结构之前我无法正确定义它.

我发现,如果我只是将函数指针的参数列表留空,那么SEEMS就可以工作了,虽然我读到的是这可能充满了问题.

以下是我目前的情况:

#include <stdio.h>

typedef void (*IO_fun_ptr_t)();

typedef struct IO_config_t{
  int                   address;
  IO_fun_ptr_t          IO_fun_ptr; //pointer to the function to be used
} IO_config_t;

void print_address (IO_config_t *input){
  printf("The address is %d \n", input->address);
  printf("Push any key to continue:");
  getchar();
}

void main()
{
  IO_config_t             input = {.address = 16,
                                   .IO_fun_ptr = &print_address};

  input.IO_fun_ptr(&input);

}
Run Code Online (Sandbox Code Playgroud)

结果是:

The address is 16 
Push any key to continue:
Run Code Online (Sandbox Code Playgroud)

这有效,但我担心将该论点留空可能会产生影响.

暂时不说,我原本以为我应该能够使用void*作为参数作为指向未知参数类型的指针的占位符,但是当我在指定指针的位置这样做时会遇到编译错误我的功能:

typedef void (*IO_fun_ptr_t)(void *);
Run Code Online (Sandbox Code Playgroud)

(错误[Pe144]:类型为"void(*)(IO_config_t*)"的值不能用于初始化"IO_fun_ptr_t"类型的实体)

关于如何做得更好,更清洁的任何建议?

abe*_*nky 6

使用前向声明.

这是一种表明结构存在的方式,但是直到后来才提供结构的所有成员的细节.

#include <stdio.h>

// 1.) Forward declaration: Here is the name of the structure
// but member-details are omitted.
struct IO_config_t;

// 2.) typedef of the structure
// Still no details on the members.
typedef struct IO_config_t  IO_config_t;

// 3.) The parameter to the function is listed, using the definition
// from step 2.)  (note: Still no details on the members yet)
typedef void (*IO_fun_ptr_t)(IO_config_t* input);

// 4.) Now we actually detail the members of the structure
struct IO_config_t{
  int                   address;
  IO_fun_ptr_t          IO_fun_ptr;
};

void print_address (IO_config_t *input){
  printf("The address is %d \n", input->address);
  printf("Push any key to continue:");
  getchar();
}

void main()
{
  IO_config_t             input = {.address = 16,
                                   .IO_fun_ptr = &print_address};

  input.IO_fun_ptr(&input);

}
Run Code Online (Sandbox Code Playgroud)

这在短程序中得到证明:https: //ideone.com/p3jBYt