Search code examples
c++arraystiming

error in two-dimensional array code


I wrote a multiplication table like this:

#include <iostream>
#include <conio.h>
using namespace std;
int main(){
    int table[9][9], i, j;
    for (i = 0; i < 10; ++i){
        for (j = 0; j < 10; ++j)
        {
            table[i][j] = (i + 1) * (j + 1);
            cout << table[i][j] << "\t";
        }
        cout << endl;
    }
    _getch();
    return 0;
}

And when I run it it gives me the right answer but when I press a key it throws this error:

 run time check faliure #2-stack around the variable table was corrupted

But it doesn't throw that error when I change the code to this:

......
int main(){
    **int table[10][10]**, i, j;
    for (i = 0; i < 10; ++i){
......

If they both give the same answer then what's the difference??


Solution

  • You are overflowing your arrays, The max index in bounds is 8 (since the indices are zero based and you defined 9 cells as your dimensions size so 8 will be the last cell in each dimension) and your for loop can reach till 9 (including 9) which will cause an overflow.