c++中奇怪的char数组输出

strange char array output in c++

本文关键字:char 数组 输出 c++      更新时间:2023-10-16

我遇到了一个奇怪的问题。在C++中

char s[]="123abc89";
cout<<s[0]<<endl;  //1  it is right
cout<<&s[0]<<endl; // I can't understand why it is "123abc89"

提前非常感谢。

s[0]是字符数组的第一个元素。&s[0]是第一个元素的地址,与数组的地址相同。给定一个字符数组的起始地址,std::cout使用以下运算符<lt;:

// prints the c-style string whose starting address is "s"
ostream& operator<< (ostream& os, const char* s);

如果你想打印字符数组的起始地址,一种方法是:

// std::hex is optional. It prints the address in hexadecimal format.  
cout<< std::hex << static_cast<void*>(&s[0]) << std::endl;

相反,这将使用运算符<lt;:

// prints the value of a pointer itself
ostream& operator<< (const void* val);

您正在深入了解C(和C++)如何处理字符串(而不是C++的std::string)。

字符串由指向其第一个字符的指针引用。下面的代码显示了这一点:

char *ptr;
ptr = "hellon";
printf("%sn", ptr);
ptr++;
printf("%sn", ptr);