&安培;运算符不生成char地址

时间:2016-10-21 09:18:18

标签: c++

我理解指针是什么,但对于字符和字符串,我很困惑。我有一段代码如下:

#include <iostream>

using namespace std;

int main ()
{
   char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

   cout << "Address of 'H' is: "; // line 1
   cout << &greeting << endl;     // line 2
   cout << "Address of 'e' is: "; // line 3
   cout << &(greeting[1]) << endl;// line 4
   cout << "Address of 'l' is: "; // line 5 
   cout << &(greeting[2]) << endl;// line 6

   return 0;
}

,输出为:

Address of 'H' is: 0x7fff30f13600
Address of 'e' is: ello
Address of 'l' is: llo

有人可以帮助我解释为什么line 4line 6不会产生地址吗?

2 个答案:

答案 0 :(得分:2)

在这种情况下,它与地址操作符&无关。

运营商

std::ostream& operator<<(std::ostream&, const char*);

是输出NUL终止的C字符串的专用重载。

如果您要打印地址,请使用强制转换为void*

cout << (void*)&greeting[1] << endl;

答案 1 :(得分:0)

因为字符串实际上是一个charachter数组。

当打印cout&lt;&lt;问候

它相当于cout&lt;&lt;及(问候[0])

从第一个字符的地址开始打印字符,直到你遇到空终止符。