Search code examples
c++castingc-strings

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


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

Solution

  • 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.