Reputation: 692
I have this function:
void TraverseRecursive ( Node * head, void (*visit) (Node *) )
{
if ( head != nullptr )
{
visit( head ) ;
TraverseRecursive( head->next, visit ) ;
}
}
And I'm trying to call it in main.cpp with
TraverseRecursive ( head, TraverseRecursive ) ;
Which gives me the error "argument of type "void (*)(Node *head, void (*visit)(Node ))" is incompatible with parameter of type "void ()(Node *)" "
So how do I correctly call it? I am just learning linked lists and obviously don't understand what
void (*visit) (Node *)
means at all.
Upvotes: 2
Views: 1160
Reputation: 385647
The second argument should be a function to call back for every node in the list. It only takes a single parameter (the node to "visit").
void visitor(Node *node)
{
printf("%s\n", node->data); // Or whatever
}
TraverseRecursive( head, visitor ) ;
Side note: What wasteful use of recursion. If you're lucky, the compiler will optimize it away. You should be using
void TraverseRecursive( Node * head, void (*visit) (Node *) )
{
for (; head != nullptr; head = head->next)
{
visit( head ) ;
}
}
Upvotes: 1
Reputation: 1921
void (*visit) (Node *)
means "pointer to a function taking one argument of type Node* and returning void". But TraverseRecurive takes two argumenst and is therefore of different type. You need to define a function like
void doSomething(Node* n)
{
}
and pass it to TraverseRecursive
Upvotes: 0