在 C 中作为参数的函数

Functions as parameters in C

我目前正在从事介绍 C class 的项目,我们基本上是在 C 中创建散列 table 实现,但我当前的问题是关于某个函数是如何用代码编写的我的教授提供的骨骼。这是创建方法的 header 定义:

     Table* create(long (*hash)(void* key),
          bool (*equals)(void* key1, void* key2),
          void (*print)(void* key1, void* key2));

这似乎是指向函数的指针作为参数?我什至不确定如何调用它,或者调用它时会发生什么。我什至不确定这些方法(散列、等于和打印)从何而来。任何帮助将不胜感激。谢谢

是的,这是一个接受三个函数指针作为参数和 returns 一个指向 Table 的指针的函数。要使用它,您必须定义三个满足给定条件的函数:

long my_hash(void *key) { ... }
bool my_equals(void *key1, void *key2) { ... }
void my_print(void *key1, void *key2) { ... }

然后用它们调用函数:

t = create(my_hash, my_equals, my_print);

这看起来像是要创建一个散列table,你必须给它一个散列函数和比较函数。打印功能可能只是为了调试。

This appears to be pointers to functions as parameters?

是的。没错。

I'm not sure how to even call this, or what happens when it is called.

您需要使用符合signat的函数 参数的 ures 并使用这些函数调用 create。示例:

long myHashFunction(void* key) {...}
bool myEqualsFunction(void* key1, void* key2) {...}
void myPrintFunction(void* key1, void* key2)) {...}


Table* table = create(myHashFunction, myEqualsFunction, myPrintFunction);

create 对这些功能的作用取决于只能猜测。我不知道它对他们有什么作用。

这应该是一条评论 - 太啰嗦不适合

Those are function pointers:
          long (*hash)(void* key),  <- returns a long, uses a void * as input
          bool (*equals)(void* key1, void* key2), <- return 0 or 1            (True/False)
          void (*print)(void* key1, void* key2)); <- no return

因为这些是指针,实际的函数名称是您创建的名称(或者教授可能已经为您创建了任何名称,包括散列、等于和打印)。

但是 "hash" returns 到散列 table(可能是数组)的偏移量。 "equals" 测试两个输入值是否具有相同的哈希值 - 相同性可能纯粹是主观的。问你的教授。 print 显示一个散列条目,这意味着我想,它会找到该条目并打印散列数组或对象中的信息以获取键值。查找 'associative array' 了解我的意思。

This appears to be pointers to functions as parameters?

是的。

I'm not sure how to even call this

要调用函数create,请传递一些具有正确类型的函数的地址以调用create

create(&f1, &f2, &f3);

or what happens when it is called.

create 主体中的任何位置(*)调用指向的函数,实际函数(例如 f1)最终会使用提供的参数进行调用。它可能是 (*equals)(k1, k2); 作为一个可能发生在 create.

中的虚构示例

(*) 或者,在这种情况下,另一个函数将从 create 分配的结构中获取函数指针,它将存储它们


事实上,C 允许您在第一种情况下编写 create(f1, f2, f3);,在第二种情况下编写 equals(k1, k2);,但这只是为了方便。