Can someone explain this to me:
char* a;
unsigned char* b;
b = a;
// error: invalid conversion from ‘char*’ to ‘unsigned char*’
b = static_cast<unsigned char*>(a);
// error: invalid static_cast from type ‘char*’ to type ‘unsigned char*’
b = static_cast<unsigned char*>(static_cast<void*>(a));
// everything is fine
What makes the difference between cast 2 and 3? And are there any pitfalls if the approach from 3 is used for other (more complex) types?
[edit] As some mentioned bad design, etc...
This simple example comes from an image library which gives me the pointer to the image data as char*
. Clearly image intensities are always positive so I need to interpret it as unsigned char
data.
static_cast<void*>
annihilate the purpose of type checking as you say that now it points on "something you don't know the type of". Then the compiler have to trust you and when you say static_cast<unsigned char*>
on your new void*
then he'll just try to do his job as you ask explicitely.
You'd better use reinterpret_cast<>
if you really must use a cast here (as it's obvioulsy showing a design problem here).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With