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

string a = "asdf"; cout<<&a[0]; cout<<a[0]; 

Why are these two outputs different from each other? Why is &a[0] not an address, but an entire line?

+7
c ++ string
source share
3 answers

&a[0] is of type char * . The stream operator << intentionally overloaded for const char * arguments to output a zero-terminated string (C-style string) that starts at this address. For example. if you do

 const char *p = "Hello World!"; cout << p; 

this is an overloaded version of << , which ensures that the string "Hello World!" sent to the output, not the value of the pointer.

And this is exactly what causes your code to output the entire line. Since C ++ 11 std::string objects are required to store their data in the form of strings with zero completion, and &a[0] is nothing more than a pointer to the beginning of a string stored inside your a object.

+13
source share

When printing a pointer to the output stream of the standard library, if it is char* or const char* , the zero-terminated string that it points to will be printed, not the address itself. If you want to print the address:

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

(Trivia: if the type of the pointer is not converted to const void* either --- because it is a pointer to a function or a pointer to a member, or it is volatile, then it will be converted to bool .)

+1
source share

&a[0] gives type char* . This is the type for which operator<<() overloaded. This particular overload prints characters starting with an address until it finds a null character, '\0' . It will not print the address as you expected.

Since you need an address, there is std::addressof() in the standard library:

 std::cout << std::addressof(a[0]); 

you can also use void* , which is almost similar to the above option:

 std::cout << static_cast<void*>(&a[0]); 
+1
source share

All Articles