有没有办法将
char[]
转换为unsigned char*
?char buf[50] = "this is a test";
unsigned char* conbuf = // what should I add here
char[]
转换为unsigned char*
?char buf[50] = "this is a test";
unsigned char* conbuf = // what should I add here
reinterpret_cast<unsigned char*>(buf)
。
expr.reinterpret.cast
第7款。
我认为这意味着可以将对象的指针显式转换为不同类型对象的指针。原始类型产生原始指针值,这种指针转换的结果是未指定的。
*reinterpret_cast<unsigned char*>(buf) = 'a'
是未指定的,但*reinterpret_cast<char*>(reinterpret_cast<unsigned char*>(buf)) = 'a'
是可以的。unsigned char *conbuf = (unsigned char *)buf;
char *
来规避严格别名规则(这意味着“使用指向[[un]signed] char的指针访问任何类型对象的内存是合法的”)。请参见此链接:https://dev59.com/43VD5IYBdhLWcg3wE3Ro#99010您可以使用char*进行别名处理<...>规则允许char*(包括signed char和unsigned char)的例外情况。始终假定char*与其他类型别名。但是反过来不起作用:没有假设您的结构体与字符缓冲区别名。
- HolyBlackCat