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; }

19th Apr 2021, 4:13 PM
Edward Finkelstein
Edward Finkelstein - avatar
4 Antworten
+ 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.
19th Apr 2021, 4:42 PM
Shadow
Shadow - avatar
+ 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).
20th Apr 2021, 7:54 AM
Shadow
Shadow - avatar
0
Shadow I dont’t get why a1 byte layout is 0x 28 00 00 00? The rest makes sense though, thanks
20th Apr 2021, 2:13 AM
Edward Finkelstein
Edward Finkelstein - avatar
0
Shadow Ah ok, that is 40 in hexadecimal, thanks
20th Apr 2021, 10:33 AM
Edward Finkelstein
Edward Finkelstein - avatar