Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between a[0] and &a[0] in string

Tags:

c++

string

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?

like image 812
celtspirit Avatar asked Jan 26 '15 23:01

celtspirit


2 Answers

&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.

like image 167
AnT Avatar answered Nov 10 '22 00:11

AnT


&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]);
like image 28
David G Avatar answered Nov 10 '22 01:11

David G