I want to know what the program does memory-wise during runtime as it comes across the following:
char chr = 'a';
char chrS[] = "a";
cout << "Address: " << &chr << endl;
cout << "Address: " << &chrS << endl;
This produces the following:
Address: a�c�3�
Address: 0x7fff33936280
Why can’t I get the memory address of “chr”?
Because
&chryields achar*(implicit addition ofconsthere) andcoutassumes that it is a string and therefore null terminated, which it is not.However,
&chrSyields achar(*)[], which will not decay to aconst char*and therefore will be output through theoperator<<(std::ostream&, const void*)overload, which prints the address.If you want this behaviour for a
const char*you will have to perform an explicit cast. The fact that there is no difference between a C-string and a pointer to a single character is one of the primary flaws of C-strings.