Link to home
Start Free TrialLog in
Avatar of SpaceMonkey101
SpaceMonkey101

asked on

Trouble with a two dimensional array - one element replaceing another

I have been trying to write a simple program of connect4 using a 4x4 array. It certiantly sounds simple but for some reason I am having problems with the array itself

#include <iostream>
using namespace std;

void main()
{
      int grid[3][3];
      for(int m=0;m<4;m++)
      {
            for(int n=0;n<4;n++)
            {
                  grid[m][n]=0;
            }
      }
      cout<<grid[0][0]<<" "<<grid[0][1]<<" "<<grid[0][2]<<" "<<grid[0][3]<<endl;
      cout<<grid[1][0]<<" "<<grid[1][1]<<" "<<grid[1][2]<<" "<<grid[1][3]<<endl;
      cout<<grid[2][0]<<" "<<grid[2][1]<<" "<<grid[2][2]<<" "<<grid[2][3]<<endl;
      cout<<grid[3][0]<<" "<<grid[3][1]<<" "<<grid[3][2]<<" "<<grid[3][3]<<endl;
      cout<<endl;
      grid[1][0]=1;
      grid[2][3]=1;
      cout<<grid[1][0]<<" "<<grid[0][3]<<" "<<grid[2][3]<<" "<<grid[3][0]<<endl;
      grid[0][3]=2;
      grid[3][0]=2;
      cout<<grid[1][0]<<" "<<grid[0][3]<<" "<<grid[2][3]<<" "<<grid[3][0]<<endl;
}

After a significant amount of frusteration I scrapped the entire code and tried this code.  The only problem is, after they are all initalized to 0, it prints out the grid perfectly.  When I go to assign values however, any value I put in grid[1][0] ends up in grid[0][3] and vice versa.  Also anything in grid[2][3] ends up in grid[3][0].  My Dev enviroment is Microsoft Visual C++, I installed it on my other computer just to make sure it wasn't a memory problem, but got the exact same result.

This is my first question here so I am still a bit fuzzy on how this works.
Avatar of avizit
avizit

int x[10];
means you have 10 integers  x[0] to x[9];


similarly for int grid[3][3];

grid[3][3] is out of bounds.


/abhijit/
ASKER CERTIFIED SOLUTION
Avatar of avizit
avizit

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of SpaceMonkey101

ASKER

Wow, thank you... I knew it was something stupid... heh
the arry declared is int grid[3][3]
and initialized with 4x4, which is Array boudary write(ABR/ABW).
that is the reason you print such result.