-3

Doing a sort function exercise for pointers to functions, so I'm writing a comparison function for char*.

cmp2(const void *p, const void *q)

How do I convert the void *p to char* ?

I tried const char* cp = static_cast<const char *>(p); but it doesn't work...

I don't want to use C-style casting like (const char *)p or something like that

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
Asphodel
  • 180
  • 1
  • 1
  • 11

1 Answers1

1

static_cast<const char *> should work fine!

The following code snippet demonstrates it.

#include <iostream>

bool compare(const void *p, const void *q){
        const char * casted_p = static_cast<const char*>(p);
        const char * casted_q = static_cast<const char*>(q);
        return *casted_p == *casted_q;
}

int main(int argc, char * argv[]) {

        char c1 = '6';
        char c2 = '6';

        const char *p1, *p2;

        p1 = &c1;
        p2 = &c2;

        if(compare(p1,p2)){
                std::cout << "equal" << std::endl;
        } else {
                std::cout << "diff" << std::endl;
        }

        return 0;
}

This will print equal.

If one character is changed to something else, e.g 7, it will print diff.

I am not sure what would be the purpose of such a function, but it can be done!

Note: If what you are up to is type erasure, consider templates! It is safer and more modern approach. Using void * for such a purpose is still C-style.