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,