新手求助,此程序为什么不能正常运行?

MTSXC 2012-04-12 12:30:36
这段程序为什么会提示:0x0042eea9指令引用的0x524f5347内存不能为read ??没有下标越界啊

#include <iostream>
#include <string>
using namespace std;
int main()
{
string *pstr=new string[10];
for(size_t index=0;index<9;++index)
{
*(pstr++)=index;
cout<<*(pstr++)<<endl;
}
delete [] pstr;
system("pause");
return 0;
}
...全文
255 17 打赏 收藏 转发到动态 举报
写回复
用AI写文章
17 条回复
切换为时间正序
请发表友善的回复…
发表回复
ghlhy0505 2012-04-20
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]

*(pstr++)=index;
cout<<*(pstr++)<<endl;
==>
*(pstr)=index;
cout<<*(pstr++)<<endl;
之前那个每次循环都两次自增,所以 越界了
[/Quote]

每次循环加两次,pstr越界那些事儿
cacasi 2012-04-20
  • 打赏
  • 举报
回复

#include <iostream>
#include <string>
using namespace std;
int main()
{
string *pstr=new string[10];
string *tempPStr = pstr;
for(size_t index=0;index<9;++index)
{
*pstr=index;
cout<<*pstr++<<endl;
}
delete [] tempPStr;
system("pause");
return 0;
}
吾子墨鸿 2012-04-17
  • 打赏
  • 举报
回复
越界了,你仔细看看
有趣是好的 2012-04-17
  • 打赏
  • 举报
回复
[Quote=引用 12 楼 的回复:]

引用 10 楼 的回复:
using namespace std;
我新学的
楼主
这句代码实干吗用的

声明命名空间中成员std。 这样声明有利于代码的简洁性。 本来应该每句都写成std::cout 而现在只需要写cout
[/Quote]
其实还蛮危险的
zhangzhizhenshuzu 2012-04-17
  • 打赏
  • 举报
回复
[Quote=引用 10 楼 的回复:]
using namespace std;
我新学的
楼主
这句代码实干吗用的
[/Quote]
声明命名空间中成员std。 这样声明有利于代码的简洁性。 本来应该每句都写成std::cout 而现在只需要写cout
laomashitu 2012-04-16
  • 打赏
  • 举报
回复
超过string *pstr=new string[10];的最大容量了
zj3344567 2012-04-16
  • 打赏
  • 举报
回复
好吧 学习一下 越界
风吹头飞扬 2012-04-16
  • 打赏
  • 举报
回复
using namespace std;
我新学的
楼主
这句代码实干吗用的
继续奋战 2012-04-15
  • 打赏
  • 举报
回复
本来想帮助楼主的。。无奈能力有限
jains521 2012-04-15
  • 打赏
  • 举报
回复
楼上的都抢答了..我跟帖
zichen0422 2012-04-15
  • 打赏
  • 举报
回复
越界了!
chris君 2012-04-14
  • 打赏
  • 举报
回复
两次自增循环,肯定会越界的。。。。
evencoming 2012-04-12
  • 打赏
  • 举报
回复
*(pstr++)=index;
cout<<*(pstr++)<<endl;
==>
*(pstr)=index;
cout<<*(pstr++)<<endl;
之前那个每次循环都两次自增,所以 越界了
北辰猫咪 2012-04-12
  • 打赏
  • 举报
回复
for(size_t index=0;index<9;++index)
{
*(pstr++)=index;
cout<<*(pstr++)<<endl;
}
改成
for(size_t index=0;index<9;++index)
{
*(pstr++)=index;
cout<<*(pstr)<<endl;
}
就行了
for循环里面pstr实际上++了两次,肯定会越界,一次for循环等于pstr += 2
yt_cloud 2012-04-12
  • 打赏
  • 举报
回复
对了,还有一个很严重的问题,指针的维护。
你都用pstr操作过地址了,所以它就不再指向初始你用new申请的那片地址了。不能删了!
yt_cloud 2012-04-12
  • 打赏
  • 举报
回复
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main(int argc, char* argv[])
{

string *pstr=new string[10];
string *p = pstr;
stringstream convert;
for(size_t index=0;index<9;++index,++pstr)
{
convert << index;
convert >> *pstr;
convert.clear();
cout<<*pstr<<endl;
}
delete [] p;
system("pause");
return 0;
}
你这程序里面有好几处问题,首先如楼上所言每次循环自加两次越界。
其次cout<<*(pstr++)<<endl;
操作符优先级不对。
最后size_t转string有问题。
我改过了,vc6,0没问题,你再看看。

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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