0
votes

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.

1
Because you need to pass only the function names: Tree * myTree = createBinTree(compstr, die); - Eugene Sh.
So that worked, but I'm not sure how to use the variables now - Bipop
The point of this API, that you are not supposed to call these functions. - Eugene Sh.
That makes so much more sense now, thank you kindly! - Bipop

1 Answers

1
votes

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. This will cause undefined behavior:

int(*compStr)(void *, void *) = &compareName;
Tree* myTree = createBinTree( ( int(*)(TreeDataTypePtr,TreeDataTypePtr ) )compstr , die );