Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Function that takes in unknown datatype c

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading