Convert char array to unsigned char*
17,769
Solution 1
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.
Solution 2
Just cast it?
unsigned char *conbuf = (unsigned char *)buf;
Related videos on Youtube
Author by
TQCopier
Updated on June 04, 2022Comments
-
TQCopier almost 2 years
Is there a way to convert
char[]
tounsigned char*
?char buf[50] = "this is a test"; unsigned char* conbuf = // what should I add here
-
HolyBlackCat about 8 yearsIf I remember the standard correctly, there is an exception that says that it is legal to use pointer to [[un]signed] char to access memory of an object of any type. I think it makes behavior of your code well-defined.
-
Motti about 8 years@HolyBlackCat I don't remember any such wording, if you could supply a reference I'll update the answer.
-
HolyBlackCat about 8 yearsUnforunately I'm unable to find a standard reference. But I found some claims on SO that there is an exception to the strict aliasing rule for
char *
(which means that "it is legal to use pointer to [[un]signed] char to access memory of an object of any type"). See this: stackoverflow.com/a/99010/2752075You can use char* for aliasing <...>. The rules allow an exception for char* (including signed char and unsigned char). It's always assumed that char* aliases other types. However this won't work the other way: there's no assumption that your struct aliases a buffer of chars.