关于指针,请各位指点!

renzha1g 2003-08-07 09:54:40
int i=50;
int *pInt = &i;
cout<<pInt<<'\n';//这样输出的是变量i的地址吧

char chA='A';
char * s =&chA;
cout<<s<<'\n';//这里的输出的为什么不是变量chA的地址呢

s="thank you";//为什么可以这样赋值呢?s不是一个指针吗?
cout<<s<<'\n';
...全文
29 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
caizzrr 2003-08-07
  • 打赏
  • 举报
回复
这个主要是字符指针的问题,如s="thank you“
这时候对指针操作时候就是对整个字符串操作,因为系统会记下字符串的首地址,当要读取字符串
时候,只要给出指针(即是地址)时,系统会读出所有的字符,直到字符串的结束符为止.
wfy 2003-08-07
  • 打赏
  • 举报
回复
都分析了就不多说了,指针功能强大,不小心就翻船¥¥
buaaaladdin 2003-08-07
  • 打赏
  • 举报
回复
int i=50;
int *pInt = &i;
cout<<pInt<<'\n';//这样输出的是变量i的地址吧//是的

char chA='A';
char * s =&chA;
cout<<s<<'\n';//这里的输出的为什么不是变量chA的地址呢//cout对象把字符指针看作字符串来输出

s="thank you";//为什么可以这样赋值呢?s不是一个指针吗?//常量字符串赋值时取其首地址,所以是char*
cout<<s<<'\n';
lgsnake 2003-08-07
  • 打赏
  • 举报
回复
第一个问题正确。 注意你并没有写 cout<<*pInt, 所以显示的是地址,等价于
printf(" %p", pInt);

第二个问题, 已经隐式的重载了超操作符, 楼2 分析的很正确!

第三个问题, char* s = "thank you";
在执行此命令时, 系统已经为指针s分配好了存储空间。将地址传给指针s
等价于
char* s = NULL;
s = "thank you"; 传的时地址
jim77 2003-08-07
  • 打赏
  • 举报
回复
A char* has special meaning in many functions that deal with string processing (which streams do). So if you do the first cout << s << '\n', it will try to treat the char * as a string, and will give you undefined results. It will start printing at chA and go until it finds a NULL character, which may be the next element or may be well down the road. In doing this, it could try to access memory that your application doesn't own or memory that is already used by a different variable in the system. To get the pointer address, you actually will need to cast it to the appropriate size for your system. For instance, in a 32-bit architecture, you might try cout << reinterpret_cast<long>(s) << '\n';.

For the "thank you", when you put a string literal in the code, the compiler will reserve space for it in the data table. The pointer will be assigned to the address in the data table. This will be read-only, though. If you try to change it (e.g. s[2] = 'W'), you will probably get an access violation error.

njuhuangmy 2003-08-07
  • 打赏
  • 举报
回复
上面的 s 是取从那个字符开始的 4 个字节的内容

如果 超过 4 个字节,可以自动 扩展

不足的话, 会在 后面 自动 补上。

cout<<s 输出的 是 s 的内容 。 原因 参看 上一个 回复
njuhuangmy 2003-08-07
  • 打赏
  • 举报
回复
第二个

其实, s 是当作一个字符串来看的,

第二个输出 输出 4 个字节的 内容

这里 需要 弄懂的 就是 一个 scanf("%d",&a); 和 scanf("%c",s);

的问题, 本身就是 地址,和 本身不是 地址的 问题
njuhuangmy 2003-08-07
  • 打赏
  • 举报
回复
hehe

第一个问题, 是的,没问题
第二个问题 , 搞不懂, 流的问题

第三个问题, 当然 可以, 因为 s 是一个 指针 啊
它代表一个地址,可以 进行运算
jp311 2003-08-07
  • 打赏
  • 举报
回复
因为char *的<<已经被重载了
ostream& operator << (ostream&, char *);
所以遇到char *就会显示字符
s 现在指向了一个const char []
const char arr[] = { 't', 'h', 'a', 'n', 'k', ' ', 'y', 'o' 'u' };
char* s = arr;
renzha1g 2003-08-07
  • 打赏
  • 举报
回复
请各位帮忙,谢谢

69,373

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧