-2

我正在学习 C++,并被赋予创建一个程序的任务,该程序允许用户修改一个包含 10 个整数的数组。如果用户给出的索引超出范围程序将退出。程序适用于负数和范围内的所有数字。当我输入一个高于我得到的范围的数字 10 时:

*检测到堆栈粉碎*:终止

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

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

当我运行程序时,我得到了这个:

1 1 1 1 1 1 1 1 1 1
Input index: 10

Input value: 4

Index out of range: Exit
*** stack smashing detected ***: <unknown> terminated
[1]    56 abort (core dumped)  ./edit
4

1 回答 1

1

您正在访问不属于您的数组的内存,因此该错误消息。在使用下标运算符 [] 分配值之前,您应该首先验证索引。

这是导致问题的代码片段(已注释):

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

我想指出一些事情:

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

例子:

std::array<int, 10> data;
data.fill( 1 );

您正在使用std::array这意味着您至少在使用 C++11。因此,对于数组遍历,您可以像这样使用 C++11 的range-for循环:

for ( const auto& i : data )
{
    std::cout << i << ' ';
}

如果您还不熟悉它,您可能想查看自动说明符。

我不知道您do-while在这里使用循环的原因。您可以使用简单的while无限循环(用于学习目的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;
    }
}

请查看std::array::at()执行边界检查并在违规时引发异常的成员函数。


我不确定你在用这部分做什么,因为这里的大括号std::cout是多余的:

while(i >= 0  && i < myData.size());    // do-while ends here
{
  cout << endl <<"Index out of range: Exit "<< endl;
}

也许,您对循环感到do-while困惑while


请不要忘记将来格式化您的代码。使用您的 IDE 的代码格式化功能,或者您也可以使用任何在线代码格式化网站(例如http://format.krzaq.cc/),同时在 SO 上发布您的代码。谢谢!

于 2018-09-15T04:37:20.880 回答