求助:动态数组删除出错的问题

dyengying 2009-02-23 03:28:06
#include <iostream>
#include <vector>
using namespace std;
void main()
{
vector<int> ivec;
int temp;
while(cin>>temp)
{
ivec.push_back (temp);
}
int *p =new int[ivec.size()];
for(vector<int>::iterator iter=ivec.begin();iter!=ivec.end();++iter,++p)
{
*p = *iter;
cout<<*p<<endl;
}
delete [] p;}
程序运行到此就会出现系统错误,不知道为什么,高手指点
...全文
70 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
zclever 2009-02-23
  • 打赏
  • 举报
回复
每次你都p++,最后的时候p已经指到最后了,你再删除p显然会出错。
lingyin55 2009-02-23
  • 打赏
  • 举报
回复
mark
tangshuiling 2009-02-23
  • 打赏
  • 举报
回复

#include <iostream>
#include <vector>
using namespace std;
void main()
{
vector <int> ivec;
int temp;
while(cin>>temp)
{
ivec.push_back (temp);
}
int *p =new int[ivec.size()];
for(vector <int>::iterator iter=ivec.begin();iter!=ivec.end();++iter,++p) //对p指向的地址做了人为的改变
{
*p = *iter;
cout < <*p < <endl;
}
p-=ivec.size(); //要么人为改回来,要么定义中间变量改变中间变量值
delete [] p;}



zwzzwz 2009-02-23
  • 打赏
  • 举报
回复
p指针移动了。所以错了
。正确做法你可以先把p的值缓存一下。

int *p =new int[ivec.size()];
int ×pTemp = p;
for(vector <int>::iterator iter=ivec.begin();iter!=ivec.end();++iter,++pTemp )
{
*pTemp = *iter;
cout < <*pTemp < <endl;
}
delete [] p;}
waizqfor 2009-02-23
  • 打赏
  • 举报
回复
[Quote=引用楼主 dyengying 的帖子:]
#include <iostream>
#include <vector>
using namespace std;
void main()
{
vector <int> ivec;
int temp;
while(cin>>temp)
{
ivec.push_back (temp);
}
int *p =new int[ivec.size()];
for(vector <int>::iterator iter=ivec.begin();iter!=ivec.end();++iter,++p)
{
*p = *iter;
cout < <*p < <endl;
}
delete [] p;}
程序运行到此就会出现系统错误,不知道为什么,高手指点
[/Quote]
LZ试试吧

#include <iostream>
#include <vector>
using namespace std;
void main()
{
vector <int> ivec;
int temp;
while(cin>>temp)
{
ivec.push_back (temp);
}
int *p =new int[ivec.size()];
for(vector <int>::iterator iter=ivec.begin();iter!=ivec.end();++iter,p)
{
*p = *iter;
cout <<*p <<endl;
}
delete [] p;
}

pengzhixi 2009-02-23
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 hai040 的回复:]
++p改了p
[/Quote]

up
hai040 2009-02-23
  • 打赏
  • 举报
回复
++p改了p
pengzhixi 2009-02-23
  • 打赏
  • 举报
回复
void main()//int main()
程序结尾加上return 0;

64,654

社区成员

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

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