[英]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]
不是地址而是整个字符串?
&a[0]
has type char *
. &a[0]
具有char *
类型。 Stream operator <<
is deliberately overloaded for const char *
arguments to output zero-terminated string (C-style string) that begins at that address. Stream运算符
<<
故意重载为const char *
参数,以输出从该地址开始的以零结尾的字符串(C样式字符串)。 Eg if you do 例如,如果你这样做
const char *p = "Hello World!";
cout << p;
it is that overloaded version of <<
that makes sure the "Hello World!"
正是那个重载版本
<<
确保了"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. 由于C ++ 11
std::string
需要的对象到其数据存储为零终止字符串和&a[0]
不是别的,只是一个指向存储在内部的字符串的开头a
对象。
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. 当打印指向标准库输出流的指针时,如果它是
char*
或const char*
,则将打印指向的以null结尾的字符串,而不是地址本身。 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
.) (琐事:如果指针类型不能转换为
const void*
,因为它是一个函数指针或指向成员的指针,或者它是易失性的 - 那么它将被转换为bool
。)
&a[0]
yields type char*
. &a[0]
产生char*
类型。 This is a type for which operator<<()
is overloaded. 这是
operator<<()
被重载的类型。 This particular overload prints the characters starting at the address until it finds a null-character, '\\0'
. 此特定重载打印从地址开始的字符,直到找到空字符
'\\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::addressof()
:
std::cout << std::addressof(a[0]);
you can also cast to void*
which is almost like the above variant: 你也可以转换为
void*
,这几乎就像上面的变种:
std::cout << static_cast<void*>(&a[0]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.