#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string*>p;
string *p1=0;
while (cin>>*p1)
{
(p).push_back(p1);
}
return 0;
}
程序为何一运行就崩溃?如果需要在堆中开辟新内存空间,那么我要问为什么不能直接用栈的内存空间而非要用堆的空间?
怎么改才能正确输入字符串而不使程序崩溃 另外编译时还没有警告提示?..
不好意思 少段程序 上面那段程序之后加上这个
for(vector<string*>::iterator i=p.begin();i<p.end();++i)
{
cout<<**i<<endl;
cout<<strlen((**i).c_str())<<endl;
}
for( i=p.begin();i<p.end();++i)
{
delete *i;
cout<<"释放内存成功"<<endl;
}
我已经补上后面的程序了 你看看你这两段程序如果加上后面的程序 运行时会有什么问题出现?
追答数组是不用释放内存的,但是释放内存一般不用迭代器,用vector自带的clear函数就行。
for( i=p.begin();i<p.end();++i)
{
delete *i;
cout<<"释放内存成功"<<endl;
}
这段改为
p.clear();
delete p1; //p1要释放,这个和vector无关,push_back是拷贝过去的。
p1=NULL;