Simple C ++ pointer

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 is the difference between cast 2 and 3? And are there pitfalls if the 3 approach is used for other (more complex) types?

[edit] As mentioned, poor design, etc.

This simple example is represented by an image library that gives me a pointer to image data like char*. Clearly, image intensities are always positive, so I need to interpret them as data unsigned char.

+3
source share
7 answers

static_cast<void*> , , ", ". , static_cast<unsigned char*> void*, , , .

reinterpret_cast<>, ( obvioulsy ).

+6

, ++ void T* static_cast ( ), . char unsigned char - . reinterpret_cast.

+5

++ , cast, C, unsigned chars static_cast ( , ). , void* , ++ , ( ).

, , , void*. , ++, .. , " ". , , void* , (, ..).

+2

static_cast , , .

+2

2 3 , 3, , void *. 3, , , undefined. undefined # 3. , , , , void * , , undefined.

+1

reinterpret_cast, void*:

void* , :

char* pch;
void* p = pch;

Dropped from void*to any other pointer, only static_cast:

unsigned char* pi = static_cast<unsigned char*>(p);
0
source

be careful when you drop void *, you lose type information.

what you are trying to do is wrong and false, and errors are prone and misleading. why the compiler returned a compilation error :-)

simple example

char* pChar = NULL; // you should always initalize your variable when you declare them
unsigned char* pUnsignedChar = NULL; // you should always initalize your variable when you declare them

char aChar = -128;
pChar = &aChar;
pUnsignedChar = static_cast<unsigned char*>(static_cast<void*>(pChar));

then, although it pUnsignedChar == pChardoes not matter, we have *pUnsignedChar == 255and *pChar == -128.

I believe this is a bad joke, so bad code.

0
source

Source: https://habr.com/ru/post/1765078/


All Articles