简体   繁体   中英

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

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.

There is a demo

#include <iostream>

int main() {
    void* Name1;
    Name1 = static_cast<void*>(new std::string("Client 1"));

    void* Name2;
    std::string str1 = "Client 2";
    Name2 = &str1;
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM