&运算符不生成字符地址

& operator does not produce char addresses

本文关键字:字符 地址 运算符      更新时间:2023-10-16

我明白指针是什么,但对于字符和字符串,它对我来说很困惑。我有一段代码如下:

#include <iostream>
using namespace std;
int main ()
{
   char greeting[6] = {'H', 'e', 'l', 'l', 'o', ''};
   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不产生地址?

在本例中与&运算符的地址无关

操作符

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

是一个专门的重载,用于输出以NUL结尾的c字符串。

如果您想打印地址,使用强制转换到void*:

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

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

问候

相当于cout <<,(问候[0])

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