I am implementing a sort of a linked list, where each node has a key, a value, and the next node. I have a function called getVal
, which should take in a key, and a linked list, that returns the value corresponding to that key. The thing is, I don't know the datatype of the key, or the value. To combat that, I also pass a compare function, which I will use when checking each nodee. My current function signature is this:
void* getVal(node *list, void *key, int (*compare)(const void *, const void*)){
The problem, with this, is that when I try to call this function with a string, for example getVal(list,"test",strcmp); Which should get the key "test", it gives a warning that the pointer types are incompatible. What can I do?
CodePudding user response:
The type of the expression strcmp
is int (*)(const char *, const char *)
, which is not compatible with int (*)(const void *, const void *)
.
You'll have to write your own routine which takes two const void *
parameters and then calls strcmp
internally:
int my_strcmp( const void *s1, const void *s2 )
{
const char *ls1 = s1;
const char *ls2 = s2;
return strcmp( ls1, ls2 );
}
CodePudding user response:
Use const void* key
instead of void* key
if the function getVal
won't modify what is pointed at by key
.