2

I'm new to C++ (coming from C), and I found some strange behavior that I didn't expect.
The symbol & gets you the location of a variable. This code

int a = 2;
std::cout << &a << "\n";

will output something like 0x7fffc010cb44 which makes sense, since this is where a is stored.

But if the variable is a character:

char b = 'x';
std::cout << &b << "\n";

The output here is simply

x

What's more bizarre, is that if I add some completely unrelated variables to the program, and I output only the location of the first one

char b = 'x';
char c = 'y';
char e = 'z';
std::cout << &b << "\n";

The program outputs all of them!

xyz

This clearly has something to do with memory allocation, since the other variables have nothing to do with b, but I have no idea why this happens.
So my question is - why does std::cout << &b << "\n"; print the character stored in b instead of the memory location of b?

George
  • 320
  • 3
  • 14
  • 4
    `&b` is a `char *` and `cout` treats them as strings. [cout << with char\* argument prints string, not pointer value](https://stackoverflow.com/q/17813423) – 001 Sep 01 '21 at 12:18
  • Try this: `std::cout << static_cast(&b) << "\n";` – Eljay Sep 01 '21 at 13:04

0 Answers0