我应该用哈希表(数据链表指针数组)和一些支持函数,即插入元素、删除表来编写C++ STL容器映射(关联数组)的C实现。我已经成功地编写了所有这些,除了一个函数,它是foreach(table, function_ptr)函数,它为表中的所有数据调用传递函数(打印内容…)。
我有点困在这里,因为我不知道应该向function_ptr传递什么参数,所以它是通用的。至于现在,我认为不可能。
如果我只想给printf传递一个指针,这将很简单,foreach的原型将如下所示

foreach(table_t *t, int (*function_ptr)(const char *fmt, ...))

我会为每个这样的数据节点调用它
function_ptr("%s, %d\n", node.key, node.data)

但是如果有一天我使用这个并改变主意,我想传递我自己的函数,我就必须同时更改调用者函数和foreach函数的代码。
有什么简单的方法做这样的事吗?

最佳答案

指定“任何参数类型”的传统方法是使用如下void *

foreach(table_t *t, int (*function_ptr)(void *p))

然后可以传递每个参数的地址(可能是复杂的数据类型,如结构),函数可以将其转换回适当的类型:
struct {
  int x;
  int y;
} numbers;

// Sums the numbers in a structure
int sum(void *p) {
  numbers *n = (numbers *) p;  // Cast back to the correct type
  return n->x + n->y;
}

// Counts the number of 'a' chars in a string
int numberOfA(void *p) {
  char *s = (char *) p;
  int num = 0;
  while (s != NULL && *s != '\0') {
    if (*s == 'a') {
      ++num;
    }
  }
}

关于c - 传递的函数指针的参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10270104/

10-11 23:14
查看更多