# include bits/stdc.husingnamespacestd; int main () { char str[20]='hhh '; char* t=str; int* a; coutaendl; coutstrendl; couttendl; 返回0; }输出结果如下。
同样地,用cout输出地址,在输出int指针的地址时输出了该地址,但在输出char型指针和char数组的地址时输出了整个字符串。
原理
当遇到char类型的指针时,cout默认输出为字符串,从给定的地址开始一直查找,直到找到内容为0的地址,然后输出对应的字符串。
hint
要使输出与char指针的地址相对应,必须强制将char指针转换为int指针输出。
代码如下所示。
# include bits/stdc.husingnamespacestd; int main () { char str[20]='hhh '; char* t=str; int* a; coutaendl; cout(int* ) strendl; cout(int* ) tendl; 返回0; }输出结果如下。