Why casting a char array into an int pointer and writing to it with a pointer makes the data upside down?

I have created some simple code to check if a char array is cast to an int pointer. This works fine, as I expected, but when I wrote to the array using a pointer, the data was replaced by MSB ↔ LSB when I print array c. Why is this happening? Does it depend on the OS?

#include "stdio.h" const int SIZE = 12; int _tmain(int argc, _TCHAR * argv[]) { unsigned char c[SIZE] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; unsigned int * ptr = (unsigned int * ) c; int i; printf("Int size=%d\n", sizeof(unsigned long)); for (i = 0; i < sizeof(c); i++) { printf("%X, ", c[i]); } printf("\n\n"); for (i = 0; i < sizeof(c) / sizeof(unsigned long); i++) { * ptr++ = i; } for (i = 0; i < sizeof(c); i++) { printf("%X, ", c[i]); } printf("\n"); return 0; } 

Here is the result:

 Int size=4 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 
+6
source share
3 answers

Your architecture contains Little Endian, which means the low byte is stored first in memory:

enter image description here

In your case, 0x00000001 is written in the order [0x01, 0x00, 0x00, 0x00].

+10
source

This is due to the endianness of your processor architecture. Your architecture seems a bit endian to trigger such inversions.

+8
source
  • You are confused because English is a Big-endian annotation .
  • Read from left to right.

For example: 0xDead is stored as

  0xD 0xE 0xA 0xD 0xADDR 0xADDR+1 0XADDR+2 0xADDR+3 
+2
source

Source: https://habr.com/ru/post/987775/


All Articles