C++ 为什么程序在结束后失败
我希望有人能回答这个问题,并实际上教我一些东西。我有一个简单的代码片段,它可以正常工作,但在程序结束后,Windows会抛出以下错误 program.exe已停止工作。问题导致程序停止 工作正常。Windows将关闭该程序,并在出现错误时通知您 解决方案是可用的 用一个按钮关闭程序 下面讨论的代码询问用户将有多少玩家,然后根据玩家数量创建一个大小等于玩家数量的数组。然后,for循环将每个字符名称打印到屏幕上。这是密码C++ 为什么程序在结束后失败,c++,arrays,visual-c++,C++,Arrays,Visual C++,我希望有人能回答这个问题,并实际上教我一些东西。我有一个简单的代码片段,它可以正常工作,但在程序结束后,Windows会抛出以下错误 program.exe已停止工作。问题导致程序停止 工作正常。Windows将关闭该程序,并在出现错误时通知您 解决方案是可用的 用一个按钮关闭程序 下面讨论的代码询问用户将有多少玩家,然后根据玩家数量创建一个大小等于玩家数量的数组。然后,for循环将每个字符名称打印到屏幕上。这是密码 int main() { int numplay;
int main()
{
int numplay;
cout<<"How many players will there be? ";
cin>> numplay;
cin.ignore();
cin.get();
string *players = new string[numplay - 1];
for (int x = 1; x < numplay + 1; x++) {
string name;
cout<<"What is Player "<< x <<"'s name? ";
cin>> name;
players[x - 1] = name;
cin.ignore();
}
cin.clear();
cin.sync();
cin.get();
for (int x = 0; x < numplay; x++) {
cout<< players[x] <<"\n";
}
delete[] players;
}
intmain()
{
int numplay;
不可能;
cin.ignore();
cin.get();
string*players=新字符串[numplay-1];
对于(intx=1;xstring*players=新字符串[numplay-1];
对于(intx=1;x cout您正在访问超出范围的数组。正如您所暗示的,从数组分配中删除-1
可以使其正常工作
string *players = new string[numplay - 1]; // Wrong
如果用户输入3
,那么您将只分配一个包含2个元素的数组。该数字表示元素的数量,而不是最大索引
正确的代码是:
string *players = new string[numplay];
我还建议对在数组上运行的任何循环使用基于零的索引。看到类似于上行的循环会让人困惑。请改为:
for (int x = 0; x < numplay; x++) {
cout << "What is Player "<< x+1 <<"'s name? ";
cin >> players[x];
cin.ignore();
}
for(intx=0;x 您是否可以分配numplay-1
数组元素,例如元素0
…numplay-2
string *players = new string[numplay - 1];
但是在循环中,您可以从0
到numplay-1
访问元素,这是数组之外的一个元素
for (int x = 1; x < numplay + 1; x++) {
...
players[x - 1] = name;
}
修复您的问题。因为现在,数组元素从0
变为numplay-1
,这与for循环中的访问相匹配
for (int x = 1; x < numplay + 1; x++) {
...
players[x - 1] = name;
}
string *players = new string[numplay];