string a = "asdf";
cout<<&a[0];
cout<<a[0];
Why are these two outputs different? Why is &a[0]
not the address but the whole string?
&a[0]
has type char *
. Stream operator <<
is deliberately overloaded for const char *
arguments to output zero-terminated string (C-style string) that begins at that address. E.g. if you do
const char *p = "Hello World!";
cout << p;
it is that overloaded version of <<
that makes sure the "Hello World!"
string itself is sent to output, not the pointer value.
And this is exactly what makes your code to output the entire string as well. Since C++11 std::string
objects are required to store their data as zero-terminated strings and &a[0]
is nothing else than a pointer to the beginning of the string stored inside your a
object.
&a[0]
yields type char*
. This is a type for which operator<<()
is overloaded. This particular overload prints the characters starting at the address until it finds a null-character, '\0'
. It won't print the address like you'd expect.
Since you need the address, there's std::addressof()
in the standard library:
std::cout << std::addressof(a[0]);
you can also cast to void*
which is almost like the above variant:
std::cout << static_cast<void*>(&a[0]);
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