[英]Why pointer returns value and not address?
This code: 这段代码:
string str1 ( "Hello world" );
const char *c_str1 = str1.c_str ( );
cout << "The C-style string c_str1 is: " << c_str1
generates this output: 生成以下输出:
The C-style string c_str1 is: Hello world
and I do not understand it. 我不明白。
c_str1
is a pointer, right? c_str1
是一个指针,对不对? So, c_str1
should return an address and only *c_str1
should give the value located at this address. 因此,
c_str1
应该返回一个地址,只有*c_str1
应该给出位于该地址的值。 However, in the above example c_str1
gives the value (not the address). 但是,在上面的示例中,
c_str1
给出了值(而不是地址)。
What do I misunderstand? 我误会什么?
It's because of how std::cout::operator <<
is defined - it has an overload that takes a const char*
and prints the string it points to. 这是因为
std::cout::operator <<
的定义方式-它有一个重载,它需要一个const char*
并输出它指向的字符串。 If you want the address, you'll have to cast to void*
. 如果需要地址,则必须强制转换为
void*
。
"What do I misunderstand?" “我误会什么?” The definition of
<<
on a char const*
. 在
char const*
上的<<
的定义。 The pointer is passed by value, but the definition of operator<<( std::ostream&, char const* )
specifies that it treat the pointer as the start of a '\\0'
terminated string. 指针按值传递,但
operator<<( std::ostream&, char const* )
指定将指针视为以'\\0'
结尾的字符串的开头。
The variable c_str1
is a pointer to the first character in the string. 变量
c_str1
是指向字符串中第一个字符的指针。 &c_str1
is a pointer to c_str1
(ie a pointer to a pointer). &c_str1
是指向c_str1
(即指针的指针)。 *c_str1
is the value at the location pointed to by c_str1
(ie only a single character). *c_str1
是在该位置的值由指向c_str1
(即只有一个字符)。
The output operator has an overload that takes a pointer to a character (what c_str1
is) and prints it as a string. 输出运算符具有一个重载,该重载采用指向字符(
c_str1
是)的指针并将其打印为字符串。
There is an overload of ostream& operator<<
for const char*
, which assumes the pointer points to the first character in a null terminated string , and prints the whole string. const char*
的ostream& operator<<
重载 ,它假定指针指向以空终止的字符串中的第一个字符,并输出整个字符串。
You can see an example of this assumption being applied somewhere it shouldn't here: 您可以在不应该在此处使用的地方看到此假设的示例:
#include <iostream>
int main()
{
char c = 'x'; // not a null terminated string
std::cout << &c << std::endl; // will write until it finds a 0 (really UB)
}
The standard specifies overloads of operator<< (ostream, char*)
which output the string stored in the pointer. 该标准指定
operator<< (ostream, char*)
重载,该重载输出存储在指针中的字符串。 In other words, c_str1
is indeed a pointer, but the output stream is interpreting it as the string it points to. 换句话说,
c_str1
确实是一个指针,但是输出流将其解释为它指向的字符串。
To output the pointer value, cast it to void*
: 要输出指针值,请将其
void*
为void*
:
cout << "The C-style string c_str1 is: " << static_cast<void*>(c_str1);
cout运算符<<将指向char的指针解释为C字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.