0
int main
{
     uint8_t a[3] ={0x4,0x3,0x1};
     uint16_t b= *((uint16_t *) a);
     cout << (int)b;
}

Result :772 So what is this number 772? Thank you!

Huy By
  • 23
  • 4
  • [This bit of handy reading discusses C](https://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule), but C++ is even more paranoid. – user4581301 Oct 30 '19 at 07:10
  • 772 in hex is 0x0304. You can start making assumptions from there, but remember they are only assumptions. – user4581301 Oct 30 '19 at 07:12
  • 2
    Note that this is undefined behavior. You may dereference a pointer only if there is an object of a given type at a place where that pointer points to. There are some exceptions, but these do not apply here. In this case, there is no object of type `uint16_t` at address `(uint16_t*)a`. What you can do safely is `memcpy(&b, a, sizeof(uint16_t));`. – Daniel Langr Oct 30 '19 at 07:26

1 Answers1

0

You need to google a bit about how array are stored in memory. When you declare

uint8_t a[3] = {0x4,0x3,0x1};

You create a block of memory that takes 3 bytes and contains 3 elements (not considering padding which is another topic).

so for

uint8_t a[3] = {0x4,0x3,0x1};

you get in memory

Byte1: 0x4
Byte2: 0x3
Byte3: 0x1

while when accessing a 16 bit variable, the compiler expects 3 elements that are each 2 bytes and take 6 bytes in total. So for

uint16_t a[3] = {0x4,0x3,0x1};

you get in memory

Byte1+2: 0x4, 0x0
Byte3+4: 0x3, 0x0
Byte5+6: 0x1, 0x0

in your case, when you cast the uint8_t array into uint16_t, you merge the 0x4 and 0x3 into 0x304 which is, as you know, 772...

Hope this helps

Lior
  • 284
  • 1
  • 6