简体   繁体   中英

Convert char array to unsigned char*

Is there a way to convert char[] to unsigned char* ?

char buf[50] = "this is a test"; 
unsigned char* conbuf = // what should I add here

Although it may not be technically 100% legal this will work reinterpret_cast<unsigned char*>(buf) .


The reason this is not 100% technically legal is due to section 5.2.10 expr.reinterpret.cast bullet 7.

A pointer to an object can be explicitly converted to a pointer to an object of a different type. original type yields the original pointer value, the result of such a pointer conversion is unspecified.

Which I take to mean that *reinterpret_cast<unsigned char*>(buf) = 'a' is unspecified but *reinterpret_cast<char*>(reinterpret_cast<unsigned char*>(buf)) = 'a' is OK.

刚施展出来的?

unsigned char *conbuf = (unsigned char *)buf;

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