suxue / cplusplus-practices-2011

Automatically exported from code.google.com/p/cplusplus-practices-2011
0 stars 0 forks source link

这是什么原因造成的? #14

Open GoogleCodeExporter opened 8 years ago

GoogleCodeExporter commented 8 years ago
  在代码段里面连续申请了两个字符指针,连续对他们用cin赋值,编译能过但是当输入第二个字符串的时候程序崩溃,这是什么原因造成的啊?
  例:

   #include<iostream.h>
   int main()
{
    char *p1,*p2;
    cout<<"请输入"<<endl;
    cin>>p1;
    cout<<"请输入"<<endl;
    cin>>p2;
    return 0;
}

Original issue reported on code.google.com by qq513193...@gmail.com on 19 Oct 2011 at 1:49

GoogleCodeExporter commented 8 years ago
cin不能读入指针,应该直接读变量
要读入字符就把*去掉

Original comment by Cdegre...@gmail.com on 19 Oct 2011 at 2:38

GoogleCodeExporter commented 8 years ago
指针是指向另一个变量的变量,另一个变量在哪儿呢?
因为你的指针没有初始化,所以我们称其为“野指针”或者��
�悬空的指针”,当你强行往里面输入(写入数据),后果自�
��难以预计了!
所以,一种可能的修改办法是:
char *p1= new char[100];
cin>>p1;
用完后,还要记得:delete []p1;

Original comment by luckyZhi...@gmail.com on 20 Oct 2011 at 2:01

GoogleCodeExporter commented 8 years ago
当然,如果希望安全的处理字符串,还有一个办法可以考虑��
�
string str;
cin>>str;

不用考虑空间分配的问题,string对象会处理的,信任她就好��
�这是面向对象的思维方式

Original comment by luckyZhi...@gmail.com on 20 Oct 2011 at 2:06