Garfield1002
Garfield1002

Reputation: 48

Strange C++ Type Casting

While following an openGL tutorial, I came across this piece of code:

unsigned char header[54];

// [...]

unsigned int dataPos = *(int*)&(header[0x0A]);

I don't understand the use of *(int*)&. Why not simply use (int) ?

Upvotes: 3

Views: 169

Answers (3)

eerorika
eerorika

Reputation: 238301

Why not simply use (int) ?'

Because (int)header[0x0A] would convert only a single byte at address 0x0A when the intention is to reinterpret a sequence of sizeof(int) bytes instead.

That said, the example has undefined behaviour because it violates "strict aliasing" rules. Also, I don't know why they cast to int* and then convert to unsigned int. A well defined alternative:

std::memcpy(&dataPos, header + 0xA, sizeof dataPos);

Upvotes: 2

yurand
yurand

Reputation: 81

Since header is a char array, the cast here is taking the address of header at the position 0x0A making it into a int* pointer and reading from that address as if it was an int. It is effectively reading 4 bytes (or the size of int on your system) of the header starting from the position 0x0A and packaging them into a single int.

The simple (int) cast would only convert the value at the position 0x0A from char to int, but would not get the values on the other 3 bytes.

Upvotes: 3

Shreeyash Shrestha
Shreeyash Shrestha

Reputation: 174

*(int*)&(header[0x0A]); means first &header[0x0A] is casted into int* to match header's type to return then * is used to de-reference the whole variable so that variable resulting isn't a pointer anymore

Upvotes: 0

Related Questions