问题描述
- 初学者对地址分配的提问
-
#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;
}
//为什么两次地址都相同?
解决方案
#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;
}
时间: 2024-10-10 14:35:42