读书人

新手此程序为什么不能正常运行

发布时间: 2012-05-13 16:39:43 作者: rapoo

新手求助,此程序为什么不能正常运行?
这段程序为什么会提示: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;
}

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

[解决办法]
#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没问题,你再看看。
[解决办法]
对了,还有一个很严重的问题,指针的维护。
你都用pstr操作过地址了,所以它就不再指向初始你用new申请的那片地址了。不能删了!
[解决办法]
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
[解决办法]
两次自增循环,肯定会越界的。。。。
[解决办法]
楼上的都抢答了..我跟帖
[解决办法]

探讨
using namespace std;
我新学的
楼主
这句代码实干吗用的

[解决办法]

#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;
}

[解决办法]
探讨

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

读书人网 >C++

热点推荐