0
Output of C++ code
Can someone explain this C++ code and its output? #include <iostream> using namespace std; int main(void) { int a1 = 40; const int* b1 = &a1; char* c1 = (char *)(b1); *c1 = 'A'; cout << *c1 << endl << *b1 << endl << a1 << endl; return 0; }
4 Respostas
+ 3
Reinterpreting b1 as a char pointer will result in a pointer to the first byte of the integer b1, its lowest memory address. It depends on the endianness of your system whether this byte is the LSB or the MSB. More about endianness:
https://en.m.wikipedia.org/wiki/Endianness
Sololearn's environment is little-endian, so the byte layout of a1 looks like this:
0x 28 00 00 00
^
|
b1 and c1 point here
Since c1 is a char pointer, it only affects a single byte. Therefore, the layout changes to the following after assignment of 'A':
0x 41 00 00 00
Interpreting 0x41 as a char will yield 'A', while interpreting all four bytes as an integer will result in 65, the ASCII-code of 'A', since all other bytes are zero.
+ 1
It's the hexadecimal representation of the bytes, hence the 0x as indicator (it's not part of the value itself). Since a byte is usually 8 bits, you can represent it with two hexadecimal digits, which incorporate 4 bits each.
The decimal value 40 is equivalent to the hexadecimal 0x28 or 0x00000028, but since in a little-endian environment, the least significant byte is stored first, the order is reversed in memory:
0x 28 00 00 00
^ ^
| |
LSB MSB
Since there is no meaningful way to access single bits, you can't really know how the byte itself is laid out in memory, but if you think of it as a single digit of a base 256 number, you can definitely say what digit it stores (40 or 0x28 in this case for the first byte, 0 for the others).
0
Shadow I dont’t get why a1 byte layout is 0x 28 00 00 00? The rest makes sense though, thanks
0
Shadow Ah ok, that is 40 in hexadecimal, thanks