Bipop Bipop - 4 months ago 22
C Question

Function Pointer help/ Pointer from integer

So I'm doing an assignment where we need to pass functions we've made ourselves into a library provided for us.

Tree * createBinTree(int (*comparePointer) (TreeDataTypePtr data1,
TreeDataTypePtr data2), void (*destroyPointer) (TreeDataTypePtr));


Is the code I've been provided.
My function pointer for the comparePointer is

int(*compStr)(void *, void *) = &compareName;


Compare is

int compareName(void * rest1, void * rest2);


But when I pass it through like so

Tree * myTree = createBinTree((compstr)(str1,str2),die(str1));


I only get an error on compstr which is "passing argument 1 of createBinTree makes pointer from integer without a cast" and "expected 'int (*)(void *, void *) but argument is of type int.

Answer

You need to pass the function, not call the function and pass the return value:

Tree* myTree = createBinTree( compstr , die );

But this is still not correct. The types of compstr and die must be compatible with the parameter types of the function createBinTree:

int(*compStr)( TreeDataTypePtr , TreeDataTypePtr ) = &compareName;

in which case, compareName must be a function of the same type. The same goes for die.


Note that only casting function pointers to the compatible type will cause undefined behavior when they are used to call the function, the original type of the function pointer must be compatible with the type used to call the function.