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 
+6
c ++ type-conversion
source share
2 answers

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


The reason this is not 100% technically legal is explained in 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 another type. the original type gives the initial value of the pointer; the result of such a conversion of the pointer is not specified.

What I mean is that *reinterpret_cast<unsigned char*>(buf) = 'a' not specified, but *reinterpret_cast<char*>(reinterpret_cast<unsigned char*>(buf)) = 'a' is fine.

+7
source share

Just drop it?

 unsigned char *conbuf = (unsigned char *)buf; 
+4
source share

All Articles