6

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
default
  • 11,485
  • 9
  • 66
  • 102
TQCopier
  • 81
  • 1
  • 1
  • 4

2 Answers2

8

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.

Motti
  • 110,860
  • 49
  • 189
  • 262
  • If 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. – HolyBlackCat Feb 23 '16 at 11:09
  • @HolyBlackCat I don't remember any such wording, if you could supply a reference I'll update the answer. – Motti Feb 23 '16 at 11:53
  • Unforunately 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: http://stackoverflow.com/a/99010/2752075 `You 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.` – HolyBlackCat Feb 23 '16 at 19:05
6

Just cast it?

unsigned char *conbuf = (unsigned char *)buf;
Dave
  • 3,438
  • 20
  • 13
  • 7
    in C++, "Just cast it" always needs a disclaimer :) – tenfour Feb 09 '11 at 12:08
  • 1
    Heh-heh! Disclaimer: This answer is fine for the text you show in the question. Don't try it on arrays of signed 8 bit numbers. – Dave Feb 09 '11 at 12:11