static_cast from 'const char *' to 'void *' is not allowed

Lincoln picture Lincoln · May 12, 2015 · Viewed 10.1k times · Source

In C++, I'm trying to print the address of a C-string but there seems to be some problem with my cast. I copied the code from a book but it just doesn't compile on my mac.

const char *const word = "hello";
cout << word << endl; // Prints "hello"
cout << static_cast< void * >(word) << endl;  // Prints address of word

Answer

zneak picture zneak · May 12, 2015

You are trying to cast away "constness": word points to constant data, but the result of static_cast<void*> is not a pointer to constant data. static_cast will not let you do that.

You should use static_cast<const void*> instead.