简体   繁体   中英

Error when attempting to static_cast<> const char[] to unsigned char *

I want to cast const char[] to unsigned char * .

I am using C++ casts (ie: static_cast ):

unsigned char * txt = static_cast<unsigned char *>("AC");

When I build the application I get the following error:

error:invalid static_cast from type 'const char [3]' to type 'unsigned char *'

When I use C like casts:

unsigned char * txt = (unsigned char *)"AC";

I don't get any compilation error and the program runs perfectly.

I MUST use C++ casts to avoid any runtime errors. How do I cast const char [3] to unsigned char * using C++ casts?

unsigned char* and const char[] are unrelated types, so that static_cast<> won't work. And the constness is different, hence a const_cast<> is required.

Correct cast:

unsigned char* txt = reinterpret_cast<unsigned char*>(const_cast<char*>("AC"));

Please note, that you cannot write through that unsigned char* txt pointer, because C++ string literals ("AC" here) are immutable and often stored in read-only memory.

See const_cast<> :

Modifying a const object through a non-const access path and referring to a volatile object through a non-volatile glvalue results in undefined behavior.

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