You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何C++代码中cout打印char指针/数组输出字符串而非地址?

Why does 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 b as a 5-element char array, but only initialized 4 characters. In C++, when you initialize an array with fewer elements than its size, the remaining elements are value-initialized — for char, that means they get set to '\0' (the null terminator). So your array b actually looks like this in memory: {'m','a','n','i','\0'}.
  • q points to the first element of b (b[0]), which is the start of this valid C-style string. When you run cout << 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:09:58