Noobish Array problems: Run-Time Check Failure #2 - Stack around the variable 'arr' was corrupted

╄→尐↘猪︶ㄣ 提交于 2019-12-11 02:22:38

问题


I'll be pretty honest/upfront here- I'm both a noob to C++, to computer programming in general, and additionally, to this site as well. I'll just preface my question by saying that I did in fact look at other questions possibly related to my own, but it just felt like they were outside of my scope. With that said, here's my problem:

I get this error message:

"Run-Time Check Failure #2 - Stack around the variable 'arr' was corrupted."

Here's my code. It's just a basic little thing for some array practice. The function multiTable outputs a multiplication table:


#include <iostream>
#include <iomanip>

using namespace std;

void multiTable();

int main()
{
    multiTable();
    return 0;
}

//Prints a 9 by 9 multiplication table;
void multiTable()
{    
    const int row = 9, col = 9;
    int arr[row][col];

    for(int i = 1; i <= row; i++)
    {
        for(int j = 1; j <= col; j++)
        {   
            arr[i][j] = j * i;
            cout << setw(3);            
            cout << arr[i][j];
        }
        cout << endl;
    }
}

I also want to mention that instead of the function call, had I just included all of the code contained within the function body in main, I don't get the run-time error. Why is it that when it's contained within a function, I get the runtime error, but when it's just in main, I don't get the error? And of course, what would I have to change in order for the function call to not produce the error?


回答1:


Those are your problems: for(int i = 1; i <= row; i++) and for(int j = 1; j <= col; j++) array counting starts from 0. So your for loops should be like this (starting from 0 and omitting the = part from <=):

for(int i = 0; i < row; i++) and for(int j = 0; j < col; j++)



来源:https://stackoverflow.com/questions/17510706/noobish-array-problems-run-time-check-failure-2-stack-around-the-variable-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!