As a newbie in C++ I've been playing around with pointers a bit. I have written the following code to interpret a short array as an integer:
#include <iostream>
int main(){
short array[2] = {10, 9};
short* pointer = array;
std::cout << pointer << ": " << *pointer << std::endl;
// 0xffffcbdc: 10
pointer++;
std::cout << pointer << ": " << *pointer << std::endl;
// 0xffffcbde: 9
int* pointer2 = (int*) array;
std::cout << pointer2 << ": " << *pointer2 << std::endl;
// 0xffffcbdc: 589834
}
Why is the value of the integer 589'834 (0009 000A) and not 655'369 (000A 0009)?
From the printed pointer addresses it looks like the array is in order in memory, why does casting to integer change that?
This behavior is undefined:
int* pointer2 = (int*) array;
You are allowed to reinterpret a pointer to T1
as a pointer to T2
only if alignment requirements of T2
are the same or less strict than alignment requirements of T1
(see reference for more details). Since alignment requirements for int
are stricter than alignment requirements for short
, your pointer re-interpretation is invalid.
Note that re-interpreting a pointer to int
as a pointer to short
would be valid.
Note: Since behavior is undefined, your program could do anything, including printing incorrect values or even crashing. However, the most likely reason for the behavior that you see is that your system stores higher bytes of an integer at lower addresses. This is one of two common options: the second one is to store higher bytes at higher addresses. These two options are called endianness. More information on it is here.
What you do is undefined behaviour, as you are violating the strict aliasing rule. Therefore, don't bother about any output you get from it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With