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

时间:2018-02-26 16:28:56

标签: c function struct function-pointers

我似乎遇到了鸡和蛋的问题。

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

我发现如果我只是将函数指针的参数列表留空,那么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);

}

结果是:

The address is 16 
Push any key to continue:

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

作为一点点,我原本以为我应该能够使用void *作为参数作为指向未知参数类型的指针的占位符,但是当我这样做时,我会得到编译错误将指针指向我的函数:

typedef void (*IO_fun_ptr_t)(void *);
  

(错误[Pe144]:类型&#34; void(*)(IO_config_t *)&#34;的值不能是   用于初始化类型&#34; IO_fun_ptr_t&#34;)的实体

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

2 个答案:

答案 0 :(得分: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);

}

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

答案 1 :(得分:0)

所以我通过堆栈交换进行了搜索,无法找到任何让我自己提问的东西。正如我即将结束所有事情一样,我会瞥一眼&#34;类似的问题&#34;在右边的方框中,我碰巧看到了之前没有遇到的以下问题:

How to properly define a function pointer in struct, which takes struct as a pointer?

在答案中,我找到了答案。我只需要在结构本身中定义函数指针,而不是在手之前。 (我曾经尝试过,但是忘了在定义中包含struct关键字,所以它没有工作,因为我猜测类型def并不完整。)

以下是编译干净并且似乎有用的内容:

#include <stdio.h>

typedef struct IO_config_t{
  int                   address;
  void                  (*IO_fun_ptr)(struct IO_config_t *); //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);
}