我正在尝试制作一个简单的 BST ADT,但我遇到了一些问题,因为我还是 C 语言的新手。
它编译,但有警告和“注意”,如果我运行程序它只打印一个元素,根节点(我希望它按顺序打印所有元素)。
我只提供了我认为必要的代码片段,如果您需要所有代码,请询问。
bst.c - BST遍历方法
41 void bst_inorder(bst b, void f(char *str)) {
42 if (b->key == NULL) {
43 return;
44 }
45 bst_inorder(b->left, f);
46 f(b->key);
47 bst_inorder(b->right, f);
48 }
测试.c
14 bst_inorder(my_bst, printf);
bst.h
10 extern void bst_inorder(bst b, void f(char *str));
我是这样编译的
gcc -O2 -W -Wall -ansi -pedantic *.c -o TEST
我收到这些警告
TEST.c: In function ‘main’:
TEST.c:14:4: warning: passing argument 2 of ‘bst_inorder’ from incompatible pointer type [enabled by default]
In file included from TEST.c:3:0:
bst.h:10:13: note: expected ‘void (*)(char *)’ but argument is of type ‘int (*)(const char * __ restrict__)’
最佳答案
警告只是因为您的参数与 printf()
函数之间确实存在不匹配。
您的函数需要 void (*)(char *)
,但 printf()
的签名是 int (*)(const char *, . ..)
。显然这些是不一样的。
这可能没问题,但最干净的修复方法是编写一个“shim”或“trampoline”函数:
static void print_node(char *str)
{
printf("%s", str);
}
然后在对 bst_inorder()
的调用中直接使用它而不是 printf
。
不确定其他问题,我认为没有足够的代码来帮助解决这个问题。
关于c - 将 printf() 作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18481431/