unsigned char myArray[10];
myArray[0] = 0;
myArray[1] = 0;
myArray[2] = 0;
myArray[3] = 22;
cout << *((int *) (myArray)) << endl;
I was shown this code in a class, but it was not explained very well. I have determined that the output is equal to (256^3)*22, but I don’t know why this is what it prints out. Can anyone explain this to me?
That code is unsafe and non-portable.
It (obviously) stores the values 0, 0, 0, and 22 in the first 4 elements of
myArray, each of which is anunsigned char(a single byte).The expression
myArrayis the name of an array, which in most contexts (including this one) “decays” to a pointer to the array’s first element, of typeunsigned char*. The cast converts theunsigned char*toint*, and the*operator defererences that pointer, yielding anintresult.So
*((int *) (myArray))takes the first 4 bytes ofmyArrayand reinterprets them as anintobject.There are at least 3 problems with this.
myArrayis correctly aligned for anintobject. It probably is, but if it isn’t the behavior is undefined; you could get a bus error, or an incorrect result, or something else altogether. (x86 processors aren’t very picky about alignment, but other systems are.)sizeof (int) == 4. Ifintis 8 bytes, then it will reinterpret the first 8 bytes ofmyArrayas anint— and 4 of those bytes are garbage.intcan vary. The main problem is byte order. Assuming nothing else goes wrong, the result could be either 2563 * 22, or 22 — or even something else.