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 &chr
yields a char*
(implicit addition of const
here) and cout
assumes that it is a string and therefore null terminated, which it is not.
However, &chrS
yields a char(*)[]
, which will not decay to a const char*
and therefore will be output through the operator<<(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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With