0

For example:

int main() {
std::string a = "hello";
std::string *b= &a;
std::cout << b;
}

This will give 0x7ffe1709... a memory address. However when we do:

  int main() {
  char a = 'A';
  char *b= &a;
  std::cout << b;
  } 

A - is printed. Why the memory address isn't printed here instead?

sherxyar
  • 83
  • 6
  • 6
    The vast majority of the time someone printing a `char *` has a nul-terminated string sitting at that pointer and wants to see the string in the output. C++ took note of this and wrote an `<<` overload to print the string, not the address. – user4581301 Mar 21 '22 at 20:03
  • 5
    The second code example invokes undefined behavior. The overload for `<<` that takes a `char *` expects a null-terminated array of char. You're lucky only `A` was printed, and not `A` and gibberish, and/or the system seg faulting/crashing on that line. – PaulMcKenzie Mar 21 '22 at 20:04
  • 3
    Personally I consider that unlucky. When you have a bug, good fortune makes you aware of it before you get humiliated at a trade show. – user4581301 Mar 21 '22 at 20:08
  • Thank you @user4581301 and Paul. I didn't know C++ over-loaded it. And I agree with you, appreciate the advice. – sherxyar Mar 21 '22 at 20:15
  • @PaulMcKenzie it was lucky, but maybe not unlikely. Chances are the compiler added padding to that single char, and the padding was zero. – Mark Ransom Mar 21 '22 at 20:22

0 Answers0