注册 登录
编程论坛 C++教室

挺奇怪的

hgxwd310 发布于 2007-09-11 23:56, 598 次点击

#include <iostream>
#include <string>

using namespace std;

int main()
{
char ch='t';
cout<<ch<<endl;
cout<<&ch<<endl;

string str="hello";
cout<<&str<<endl;
cout<<str<<endl;
cout<<str[1]<<endl;

char *p="hell0";
cout<<*p<<endl;
cout<<p<<endl;


int i=5;
cout<<&i<<endl;

char cha[]="sdfsdfsf";
cout<<cha<<endl;
cout<<*cha<<endl;
return 0;
}
它们的结果很奇怪。为什么呢???

7 回复
#2
hegj2007-09-12 00:46

试了一下,奇怪的是:
cout<<&ch<<endl; 输出 奇怪的东西
cout<<*p<<endl; 输出 h
cout<<p<<endl; 输出 hell0
这3句

#3
青格儿2007-09-12 08:43
不奇怪啊!建议你学一下指针,这是基础 你就会明白它为什么会输出那些东西了!

#4
hegj2007-09-12 10:24
cout<<&ch<<endl;
这个的输出是为什么啊?
指针不是一个整数吗?
#5
valentineyzq2007-09-12 12:06
先解释2楼后两个句:
char *p="hell0";这句是定义一个字符串,其实就是以p为起始地址的字符数组
cout<<*p<<endl;//输出p指针指向地址的内容——hell0的第一个字母
cout<<p<<endl输出p数组。这个是字符数组特有的功能——可直接cout

至于那个奇怪的输出,我以前遇到过,但也不清楚其中原因,期待高手答疑。
#6
Arcticanimal2007-09-12 15:38
字符变量的地址(也就是字符指针)不可以直接用cout输出, 这是重载的"&lt;&lt;"运算符的问题. 这样就行了 cout&lt;&lt;hex&lt;&lt;int(// pointer to a character);
#7
雨中飞燕2007-09-12 15:57
字符指针的特殊性的问题



by 雨中飞燕 QQ:78803110 QQ讨论群:5305909

[url=http://bbs.bc-cn.net/viewthread.php?tid=163571]请大家不要用TC来学习C语言,点击此处查看原因[/url]
[url=http://bbs.bc-cn.net/viewthread.php?tid=162918]C++编写的Windows界面游戏[/url]
[url=http://yzfy.org/]C/C++算法习题(OnlineJudge):[/url] http://yzfy.org/
#8
青格儿2007-09-13 09:41
你用的是Visual C++吧!我用G++没出来奇怪的字符,刚我用Visual C++运行了下,是出现了个怪字符!楼上说是:字符指针的特殊性的问题,那么可以说具体点吗?
1