2 saltyfisher saltyfisher 于 2014.10.23 20:27 提问

初学者对地址分配的提问

#include "iostream"
#include "cstring"
#include "string"
using namespace std;
string* getname();

int main()
{
string* name;
name=getname();
cout << *name << " at " << name << endl;
delete []name;
name=getname();
cout << *name << " at " << name << endl;
delete []name;
return 0;
}

string* getname()
{
string temp;
cout << "Enter your last name: ";
cin >> temp;
string* pn = new string[temp.size()+1];
//为什么去掉temp.size()+1会出错?
*pn = temp;
return pn;
}
//为什么两次地址都相同?

1个回答

VisualEleven
VisualEleven   Ds   Rxr 2015.01.04 17:02
 #include "iostream"
#include "cstring"
#include "string"
using namespace std;
string* getname();
int main()
{
    string* name;
    name=getname();
    cout << *name << " at " << name << endl;
    delete name;
    name = NULL;

    name=getname();
    cout << *name << " at " << name << endl;
    delete name;
    name = NULL;
    return 0;
}
string* getname()
{
    string temp;
    cout << "Enter your last name: ";
    cin >> temp;
    string* pn = new string;
    *pn = temp;
    return pn;
}
saltyfisher
saltyfisher 已试,但是地址任然一样,很奇怪
3 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!