为何C++代码中cout打印char指针/数组输出字符串而非地址?
cout << q print "mani" instead of the address stored in q? Ah, this is a classic gotcha with C++'s std::cout and C-style strings! Let me break down exactly what's going on here:
The core reason: std::cout has a special overload for char*
Normally, when you pass a pointer (like an int* or double*) to cout, it will print the memory address that the pointer holds. But for char* specifically, the standard library provides an overloaded version of operator<< that treats the pointer as a C-style string.
What this means is: instead of printing the address, cout will start reading characters from the memory location the pointer points to, and keep printing until it hits a null terminator ('\0').
Why your code outputs "mani"
Looking at your code:
int main(){ char *q; char b[5]={'m','a','n','i'}; q=&b[0]; cout<<b<<endl; cout<<q<<endl; }
- You declared
bas a 5-elementchararray, but only initialized 4 characters. In C++, when you initialize an array with fewer elements than its size, the remaining elements are value-initialized — forchar, that means they get set to'\0'(the null terminator). So your arraybactually looks like this in memory:{'m','a','n','i','\0'}. qpoints to the first element ofb(b[0]), which is the start of this valid C-style string. When you runcout << q, it reads from that address, prints 'm', 'a', 'n', 'i', then stops at the'\0'— hence you see "mani" instead of the address.
How to print the address instead
If you want to see the actual memory address stored in q, you need to bypass the char* overload by casting the pointer to void*. cout doesn't have a special overload for void*, so it will print the address as expected:
cout << static_cast<void*>(q) << endl;
内容的提问来源于stack exchange,提问作者Manish Sharma

