Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ short array 'reversed' when casted to integer

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?

like image 204
kalsowerus Avatar asked Nov 10 '17 13:11

kalsowerus


2 Answers

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.

like image 104
Sergey Kalinichenko Avatar answered Nov 06 '22 17:11

Sergey Kalinichenko


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.

like image 3
Jodocus Avatar answered Nov 06 '22 18:11

Jodocus