Assigning a pointer to C ++ programming

No, this is not the best way to do something. However, for the sake of theory, how could one assign the value of a pointer to a pointer to an anonymous structure?

#pragma pack(push,1) struct { __int16 sHd1; __int16 sHd2; } *oTwoShort; #pragma pack(pop) oTwoShort = (unsigned char*)msg; // C-Error 

gives:

error C2440: '=': cannot convert from 'unsigned char *' to '<unnamed-type-oTwoShort> *'

The example assumes msg is a valid pointer.

Is it possible? Since you don't have the actual type, can you even come up with?

+4
source share
4 answers

You can get the type with decltype :

 oTwoShort = reinterpret_cast<decltype(oTwoShort)>(msg); 

This was added in C ++ 11, so it will not work with older compilers. Boost implements about the same ( BOOST_PROTO_DECLTYPE ), which is designed to work with older compilers. It has some limitations (for example, if memory is used, you can use it only once for each area), but it is probably better than nothing.

+11
source

I think you need to use C ++ 11 decltype :

 oTwoShort = reinterpret_cast<decltype(oTwoShort)>(msg); 
+7
source
 reinterpret_cast<unsigned char*&>(oTwoShort) = reinterpret_cast<unsigned char*>(msg); 

But really?

+5
source

As said, you cannot cast a pointer, but you can do it:

 memcpy(&oTwoShort,&msg,sizeof(void*)); 
0
source

All Articles