动态数组问题?

freezhATsis 2009-10-07 08:50:33

#include<iostream>
#include<vector>
#include<string>
using namespace std;

int main()
{
string str;
vector<string> svec;
cout<<"Input:"<<endl;
while(cin>>str)
svec.push_back(str);
if(svec.size()==0){
cout<<"NO DATA!"<<endl;
return -1;
}
string *sp = new string[svec.size()];
string *tp = sp;//这里为什么要这样写才行,直接用sp为什么不行?
for(vector<string>::iterator it=svec.begin();it != svec.end();++it,++tp){
*tp=*it;
cout<<*tp<<" ";
}
cout<<endl;

delete [] sp;

return 0;
}
...全文
71 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
kiwigiving 2009-10-08
  • 打赏
  • 举报
回复
情况1:
string *sp = new string[svec.size()];
string *tp = sp;//这里为什么要这样写才行,直接用sp为什么不行?
for(vector<string>::iterator it=svec.begin();it != svec.end();++it,++tp)
{
*tp=*it;
cout<<*tp<<" ";
}
cout<<endl;
delete [] sp;

如果不是这样写,而是像下面一样写的话:

情况2:
string *sp = new string[svec.size()];
for(vector<string>::iterator it=svec.begin();it != svec.end();++it,++sp)
{
*sp=*it;
cout<<*sp<<" ";
}
cout<<endl;
delete [] sp;

那么会发生系统级的错误,楼主可以试一下看。
说明一下原因:
string *sp = new string[svec.size()],这里的指针sp指向的
是我们动态分配的string数组的首地址,也就是string数组第一个元素
的地址。 delete[] sp的意思是释放 指针sp指向的元素 为首元素的数
组。因此情况1能够正确释放我们动态分配的string数组。但是情况2,
我们delete[] sp,这里的sp是经过了svec.size()次的++后的sp,然后
用delete[] sp 去释放sp所指元素为首元素的动态分配数组,其实这个动态
分配的内存单元是不存在,因此我们使用deletep[] sp是对一块不存在的
自由存储区进行delete,此时,自由存储区可能会被破坏,因此这样的错误
将是毁灭性的!
freezhATsis 2009-10-08
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 kiwigiving 的回复:]

string *sp = new string[svec.size()];
for(vector<string>::iterator it=svec.begin();it != svec.end();++it,++sp)
{
*sp=*it;
cout<<*sp<<" ";
}
cout<<endl;
delete [] sp;


我就是因为这样写报错了才来问了!谢谢各位了
[/Quote]
某某9 2009-10-07
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 adventurelw 的回复:]
为了这一步而已
delete [] sp;
如果不是为了这一步,当然可以直接用sp
或者你用sp[i] = *it;也可以,总之要保留正确的数组指针以便最后释放内存。
[/Quote]有道理
adventurelw 2009-10-07
  • 打赏
  • 举报
回复
为了这一步而已
delete [] sp;
如果不是为了这一步,当然可以直接用sp
或者你用sp[i] = *it;也可以,总之要保留正确的数组指针以便最后释放内存。
illuminati 2009-10-07
  • 打赏
  • 举报
回复
tp 的作用就是保存new的string数组的首地址.利用tp代替sp进行迭代.
如果不在申请个变量保存原先申请内存的首地址,那么delete时就会产生内存泄露

64,647

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧