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

cout输出问题! 紧急

shaoyuan 发布于 2008-11-08 20:21, 1451 次点击
#include<iostream.h>
#include<string.h>
void main()
{
  char a[20],*str1="hello",*str2="wang";
  cout<<str2;
}
为什么cout输出的不是str2所指向的字符串的地址?
12 回复
#2
newyj2008-11-08 20:45
程序代码:
#include<iostream.h>
void main()
{
  char a[20],*str1="hello",*str2="wang";
  cout<<(int*)str2;
}
#3
安徽U阿朱2008-11-08 21:34
std::cout<<&str2;
#4
shediao2008-11-08 21:49
老兄能否听我一言:
#include <iostream.h>
#include <string.h>
int main(int argc, char* argv[])
{
    char *str1="shediao";
    char *str2=str1;
    cout<<(unsigned *)str1<<endl;
    cout<<&str1<<endl;
    cout<<(unsigned *)str2<<endl;
    cout<<&str2<<endl;
    return 0;
}

结果:
0x00429108
0x0012FF7C
0x00429108
0x0012FF78
所以输出字符串的地址应该为cout<<(unsigned*)str1;
而 cout<<&str1;是指输出了指针变量的地址
#5
shaoyuan2008-11-08 22:21
printf("%p\n",str2);
 如果(unsigned*)str2是输出字符串的地址,那么如果加上上面的语句为什么输出的字符串的地址为什么和用(unsigned*)str2输出的不一样啊?
#6
pascale2008-11-09 00:44
[bo][un]shediao[/un] 在 2008-11-8 21:49 的发言:[/bo]

老兄能否听我一言:
#include
#include
int main(int argc, char* argv[])
{
    char *str1="shediao";
    char *str2=str1;
    cout

奇怪,开始赋值不是把字符串首地址赋给str2了么?对于指针有些我还是不很懂。。能否解释下?我怎么觉得是一样的。。
#7
shediao2008-11-09 00:55
回复 5# 的帖子
是一样的  老兄 你可以仔细看看,
#8
shediao2008-11-09 01:01
回复 6# 的帖子
兄弟,你说的是对的 char *str="shediao"就是把字符串的首地址付给了str 但是你要输出这个字符串的首地址是要进行 类型转换,不然就会输出字符窜了,

所以 输出字符串的地址就是 cout<<(unsigned *)str;  //把str转化为无符合整形就是地址

而 cout<<&str是输出了 变量str的地址,

具体情况可以参考一下我在4楼写的代码
#9
pascale2008-11-09 01:02
额。。ms有些明白了。。
str2是指针变量仅仅存放字符串首地址
字符串是存放在以那个首地址为开头的连续内存里
#10
pascale2008-11-09 01:03
[bo][un]shediao[/un] 在 2008-11-9 01:01 的发言:[/bo]

兄弟,你说的是对的 char *str="shediao"就是把字符串的首地址付给了str 但是你要输出这个字符串的首地址是要进行 类型转换,不然就会输出字符窜了,

所以 输出字符串的地址就是 cout

类型转换?这个不太明白。。
#11
pascale2008-11-09 01:06
额,我自己仔细看看先,谢谢lsss
#12
hitcolder2008-11-09 16:25
(type)expression;就是类型转换,比如说:(float)1/2  结果不是0,是0.5

不过对于地址的输出,类型必须转换成unsigned才能输出吗,其他的就不行吗?
#13
zxf126042008-11-10 10:29
[bo][un]shaoyuan[/un] 在 2008-11-8 20:21 的发言:[/bo]

#include
#include
void main()
{
  char a[20],*str1="hello",*str2="wang";
  cout


(unsigned*)str1输出的就是字符串地址,也是不是就是字符串的首地址啊?
如果
#include<iostream.h>
#include<string.h>
void main()
{
  char a[20],*str1="hello",*str2="wang";
  
  cout<<str1<<endl;
  cout<<str2<<endl;
  cout<<(unsigned *)str1<<endl;
 
  cout<<&(*str)<<endl;
  
}
最后那两个不是应该相等的吗。。。?

[[it] 本帖最后由 zxf12604 于 2008-11-10 10:31 编辑 [/it]]
1