堆栈粉碎终止程序 我学习C++,并被赋予任务来创建一个程序,允许用户修改一个数组,其中有10个整数。如果用户给出的索引超出范围,程序将退出。该程序适用于负数和范围内的所有数字。当我输入一个数字,如10,它高于我得到的范围:

堆栈粉碎终止程序 我学习C++,并被赋予任务来创建一个程序,允许用户修改一个数组,其中有10个整数。如果用户给出的索引超出范围,程序将退出。该程序适用于负数和范围内的所有数字。当我输入一个数字,如10,它高于我得到的范围:,c++,arrays,for-loop,do-while,stack-smash,C++,Arrays,For Loop,Do While,Stack Smash,*检测到堆栈崩溃*:终止 我是新手,任何帮助都将不胜感激 #include <iostream> #include <array> using namespace std; int main() { array<int, 10> myData; // creates array size 10 int i = 0; int v = 0; for (unsigned int n = 0; n < myData.size(

*检测到堆栈崩溃*:终止

我是新手,任何帮助都将不胜感激

#include <iostream>
#include <array>
using namespace std;

int main()
{
    array<int, 10> myData; // creates array size 10
    int i = 0;
    int v = 0;

    for (unsigned int n = 0; n < myData.size(); n++) // makes all elements 1
    {
        myData[n] = 1;
    }

    do
    {
        for (unsigned int a = 0; a < myData.size(); a++)
        {
            cout << myData[a] << " ";
        }
        cout << endl << "Input index: ";
        cin >> i;
        cout << endl << "Input value: ";
        cin >> v;
        myData[i] = v;
    } while (i >= 0 && i < myData.size());
    {
        cout << endl << "Index out of range: Exit " << endl;
    }
    return 0;
}
#包括
#包括
使用名称空间std;
int main()
{
数组myData;//创建数组大小10
int i=0;
int v=0;
for(unsigned int n=0;ncout您正在访问的内存不是数组的一部分,因此出现错误消息。在使用下标运算符[]赋值之前,应首先验证索引

以下是导致问题的代码片段(注释):

cin >> v;
myData[i] = v; // Direct assignment without validating i
               // i needs to be validated before this assignment

我想指出以下几点:

对于具有相同值的初始化,您不需要循环,因为成员函数正是这样做的

例如:

std::array<int, 10> data;
data.fill( 1 );
如果你还不熟悉的话,你可能想看看

我不知道你在这里使用循环的理由。你可以使用一个简单的无限循环(出于学习目的),在无效的索引输入上使用
if-else
在赋值前验证索引

例如:

while ( true )
{
    // Print array here...

    std::cin >> index;
    if ( /* index is out of bounds */ )
    {
        std::cerr << "ERROR: Out-of-range index!\n";
        break; // Exit from loop here on invalid index
    }
    else
    {
        std::cin >> value;
        data[ index ] = value;
    }
}
也许,你把
do while
while
循环混淆了



请不要忘记将来格式化代码。使用IDE的代码格式化功能,或者在发布代码时也可以使用任何在线代码格式化网站(例如)。谢谢!

确定:
cin>>i
。太好了,您已经输入了“11”。下一步:
myData[i]=v;
--很好,您现在已经破坏了内存。您到底在哪里做了什么来检查以确保输入的
i
值在范围内?是的,该部分稍后会出现,但我担心此时马已经离开了马厩,并且您已经损坏了内存。您不能期望以随机顺序进行操作,也没有他用计算机把事情分类并按正确的顺序做。在你真正尝试访问数组之前检查一个越界索引,而不是之后。非常感谢你给了我一个非常详细的答复。这帮助我更多地理解了它。非常感谢。@JovannyElias:不客气!很高兴它有帮助。养成阅读的习惯(C++参考)[en.cppreference.com]了解语言和标准库功能,然后再使用它们。这将帮助您加快速度。祝您好运!
for ( const auto& i : data )
{
    std::cout << i << ' ';
}
while ( true )
{
    // Print array here...

    std::cin >> index;
    if ( /* index is out of bounds */ )
    {
        std::cerr << "ERROR: Out-of-range index!\n";
        break; // Exit from loop here on invalid index
    }
    else
    {
        std::cin >> value;
        data[ index ] = value;
    }
}
while(i >= 0  && i < myData.size());    // do-while ends here
{
  cout << endl <<"Index out of range: Exit "<< endl;
}