So you have your array in memory as so:
2, 23, 6, 7, 8...
What this does is cast the array to a char*
, which lets you access individual bytes, and it points here:
2, 23, 6, 7, 8...
^
It then adds four bytes, moving it over to the next value (more on this later).
2, 23, 6, 7, 8...
^
Then it turns it into an int*
and dereferences it, getting the value 23.
There are technically three things wrong with this code.
The first is that it assumes that an unsigned
is 4 bytes in size. (Hence the + 4
). But this isn't necessarily true! Better would have been + sizeof(unsigned)
, ensuring correctness no matter what size unsigned
happens to be.
The second problem is the cast to int
: the original array was unsigned
, but the value is being cast to an int
. There exists values in the unsigned
range that int
cannot represent (because in an int
half of the range is in the negatives.) So if one of the values in the array was not representable as an int
(meaning the value was greater than INT_MAX
), you'd get the wrong value. Better would be to convert to unsigned*
, to maintain the correct type.
The last thing is the format specifier. The specifier for integers is %d
, but the code uses %u
, which is for unsigned integers. In effect, even though casting back to int*
was wrong, printf
is going to cast that value back into an unsigned*
, restoring it's integrity. By fixing problem two, problem three fixes itself.
There is a hidden fourth problem: The code sucks. This may be for learning purposes, but yuck.