Reputation: 331
I'm trying to make a simple BST ADT, and I'm having some problems since I'm still new to C.
It compiles, but with warnings and a 'note', if I run the progam it only prints one element, the root node ( i want it to print all elements inorder).
I only provided code snippets that I thought was necessary, if you want all the code just ask.
bst.c - BST traversal method
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));
I'm compiling it like this
gcc -O2 -W -Wall -ansi -pedantic *.c -o TEST
and I get these warnings
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__)’
Upvotes: 0
Views: 888
Reputation: 122383
The warning is clear, the 2nd argument of bst_inorder
type mismatch.
I assume that you are trying to use printf
to print strings only(i.e, not using the variable argument part), in that case, you can wrap it like this:
void my_printf(char *str)
{
printf("%s", str);
}
And call it with:
bst_inorder(my_bst, my_printf);
Upvotes: 0
Reputation: 17848
What it says - your function is expecting a function returning void, while printf
returns int.
Other problem is that the correct syntax for pointer to function is like this:
void (*f)(char *str)
Or in case of printf
:
int (*f)(const char *)
Upvotes: 2
Reputation: 399793
The warning is simply because there really is a mis-match between your argument and the printf()
function.
Your function expects void (*)(char *)
, but printf()
's signature is int (*)(const char *, ...)
. Clearly these are not the same.
It's probably OK, but the cleanest way to fix it is to write a "shim" or "trampoline" function:
static void print_node(char *str)
{
printf("%s", str);
}
Then use that instead of printf
directly in the call to bst_inorder()
.
Not sure about the other problem, I think there's not enough code present to help with that.
Upvotes: 2