C ++ short array 'reverseed' when clicking on an integer

As a newbie in C ++, I played around with pointers a bit. I wrote the following code to interpret a short array as a whole:

#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)?

The printed address of the pointers looks like an array is in order in memory, why does casting with an integer change this?

+6
source share
2 answers

This behavior is undefined:

int* pointer2 = (int*) array;

T1 T2 , T2 , T1 (. ). int , short, .

, int short .

: undefined, , . , , , . : - . endianness. .

+8

, undefined, . , .

+3

All Articles