Reputation: 615
I have seen this type of declaration many times and have no idea what it's doing:
*(type*)$var
for example:
*(char *)&myChar
If the address of myChar
is being retrieved and it is casted to char
pointer then why the extra pointer outside and why is the address which is possibly an int or hex value being casted as a pointer? This makes no sense to me. I am a beginner so please, step by step explain what is going on here and why use this confusing format for type casting. Thank you.
Upvotes: 4
Views: 182
Reputation: 7625
*(char *)&myChar
Address of myChar
is taken, then casted to char*
, and finally the object pointed by it is accessed. The effect is that, the access will according to the casted pointer type. For example
int x;
char c = *(char*)&x;
Here x
is of type int
, but it is being accessed as char
. In effect 1 Byte, since char
size is 1 byte.
This type of casting is useful in cases like you pack several data of smaller size in a larger size. In the above case, you can store 4 characters (assuming int has size 4 Byte) in a single integer, and then access them individually. But in C++ code they are rarely used.
Upvotes: 4
Reputation: 179422
*(type *)&var
is a common C idiom for reinterpreting the bits of a value as a different type.
For example, you may sometimes see
char buf[4];
*(uint32_t *)&buf = 32;
which writes the bit representation of 32 to the array buf
.
Note: This idiom is not always safe, and is essentially non-portable. It may also break terribly if the value under consideration is not aligned correctly. Most uses are also subject to the platform's endianness. Use with extreme caution!
Upvotes: 2