is there difference between with or without * for function pointer in C?
my function pointer declaration like this
typedef void (*DListVisitNode) (Node*, void*);
void DListTraverse( NodeList* , DListVisitNode , void*);
i have code like these
void print_index( Node* node, void* ctx)
{
printf("index:%d\n", node->index);
}
void* print_content( Node* node, void* ctx)
{
printf("content:%s\n", node->content);
}
void DListTraverse(NodeList* nodelist, DListVisitNode visit_func, void* ctx)
{
Node* cur_node = nodelist->headnode;
while( cur_node != NULL)
{
visit_func( cur_node, ctx );
cur_node = cur_node->nextnode;
}
}
DListTraverse( nodelist, print_content, NULL );
DListTraverse( nodelist, print_index, NULL );
both of DListTraverse works, but the one with * throws warning like this
warning: passing argument 2 of ‘DListTraverse’ from incompatible pointer type
i would simply delete the * afterward, but what’s the difference between them?
print_contentis defined as returning avoid*i.e. a generic raw pointer.print_indexis defined as returningvoidi.e. without any results.These are different signatures. Only
print_indexmatchesDListVisitNode.My coding style is to define signature thru
typedeflikeNotice that no pointer is involved above. This names the signature of functions with one
intargument and no results.then, when needing pointers to such functions of above signature, use
signature_t*What is true is that the name of a function is like the name of an array; the language implicitly convert these to pointers. So
DListTraverse(nodelist, print_content, NULL)is understood likeDListTraverse(nodelist, &print_content, NULL)You should enable all warnings on your compiler; with
gccthat means giving-Wall -Wextraas program arguments to the compiler.