c++ - 尝试将 static_cast<> const char[] 转换为 unsigned char * 时出错

标签 c++ arrays string casting

我想将 const char[] 转换为 unsigned char *

我正在使用 C++ 转换(即:static_cast):

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

当我构建应用程序时,出现以下错误:

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

当我像转换一样使用 C 时:

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

我没有遇到任何编译错误,程序运行完美。

我必须使用 C++ 转换以避免任何运行时错误。如何使用 C++ 转换将 const char [3] 转换为 unsigned char *

最佳答案

unsigned char*const char[]是不相关的类型,因此 static_cast<>不会工作。而且常量是不同的,因此是 const_cast<>是必需的。

正确的转换:

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

请注意,您不能写通 unsigned char* txt指针,因为 C++ 字符串文字(此处为“AC”)是不可变的,通常存储在只读内存中。

参见 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.

关于c++ - 尝试将 static_cast<> const char[] 转换为 unsigned char * 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43895016/

相关文章:

C++ 入门问题

c - 将无符号字符数组返回给主函数

php - 降序排列

java - 将字符串 append 到 JTextPane

mysql - 如何使用mysql找到匹配单词后半部分的部分字符串?

java - 当 EditText 中只有一个字符时防止退格

c++ - 有哪些对二进制打包结构消息进行版本控制的好方法?

c++ - 编译后停止和仅检查语法之间的区别

java动态创建数组

c++ - 打印包含多字节字符的固定宽度字符串