0
#include "stdafx.h"
#include <iostream>
using namespace std;
#define NUMBER_OF_PLAYERS 3


int _tmain(int argc, _TCHAR* argv[])
{
    int my2DArray[3][3];
    my2DArray[1][1] = 1;
    my2DArray[1][2] = 2;
    my2DArray[1][3] = 3;

    my2DArray[2][1] = 4;
    my2DArray[2][2] = 5;
    my2DArray[2][3] = 6;

    my2DArray[3][1] = 7;
    my2DArray[3][2] = 8;
    my2DArray[3][3] = 9;

    for (int y = 0; y < 3; y++)
    {
        for(int x = 0; x < 3; x++)
        {
            cout << my2DArray[x][y]; 
        }
        cout << endl;
    }
    return 0;
}

When I run this C++ code, a message appears: Run-Time Check Failure #2 - Stack around the variable 'my2DArray' was corrupted. I checked the other threads, but didn't find the answer. What I'm doing wrong?

Kevin Le - Khnle
  • 10,579
  • 11
  • 54
  • 80
ladybug
  • 67
  • 1
  • 6
  • Read this: ["How to use arrays in C++"](http://stackoverflow.com/questions/4810664/how-do-i-use-arrays-in-c). – WhozCraig Feb 20 '14 at 04:03

2 Answers2

0

Arrays in C++ are 0-based. So a quick fix:

my2DArray[0][0] = 1;
my2DArray[0][1] = 2;
my2DArray[0][2] = 3;

my2DArray[1][0] = 4;
my2DArray[1][1] = 5;
my2DArray[1][2] = 6;

my2DArray[2][0] = 7;
my2DArray[2][1] = 8;
my2DArray[2][2] = 9;
Kevin Le - Khnle
  • 10,579
  • 11
  • 54
  • 80
0

C/C++ uses 0 based indexes for arrays. So if you make an array like int array[3], the first element is accessed by array[0]. The last element is array[2]. You get a stack corruption if you write to array[3] because it is not part of the array and you are writing to it.

nakiya
  • 14,063
  • 21
  • 79
  • 118