简体   繁体   中英

what is the difference between a[0] and &a[0] in 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?

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

When printing a pointer to a standard library output stream, if it's char* or const char* , the null-terminated string pointed to will be printed, rather than the address itself. If you want to have the address printed:

cout << static_cast<const void*>(&a[0]);

(Trivia: if the pointer type isn't convertible to const void* either---because it is a function pointer or a pointer to member or it is volatile---then it is converted to bool .)

&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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM