将printf()作为参数传递

时间:2013-08-28 07:10:08

标签: c string gcc printf

我正在尝试制作一个简单的BST ADT,因为我还是C的新手,所以我遇到了一些问题。

它编译,但有警告和'注意',如果我运行progam它只打印一个元素,根节点(我希望它按顺序打印所有元素)。

我只提供了我认为必要的代码段,如果你想要所有的代码只是问。

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    }

TEST.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__)’

3 个答案:

答案 0 :(得分:2)

警告只是因为你的论证与printf()函数之间确实存在不匹配。

您的函数需要void (*)(char *),但printf()的签名为int (*)(const char *, ...)。显然这些都不一样。

这可能没问题,但解决这个问题的最简单方法是写一个“垫片”或“蹦床”功能:

static void print_node(char *str)
{
  printf("%s", str);
}

然后在printf的调用中直接使用bst_inorder()代替{{1}}。

不确定其他问题,我认为没有足够的代码来帮助解决这个问题。

答案 1 :(得分:2)

它说什么 - 你的函数期望函数返回void,而printf返回int。

其他问题是指向函数的指针的正确语法如下:

void (*f)(char *str)

或者printf

int (*f)(const char *)

答案 2 :(得分:0)

警告很明显,bst_inorder类型不匹配的第二个参数。

我假设您正在尝试使用printf仅打印字符串(即,不使用变量参数部分),在这种情况下,您可以像这样包装它:

void my_printf(char *str)
{
    printf("%s", str);
}

并将其命名为:

bst_inorder(my_bst, my_printf);