0

I am trying to make a game like 2048 but I've encountered a problem.

    #include <iostream>
    #include <conio.h>
    #include <windows.h>
    #include <time.h>
    using namespace std;

    void random();
    void randomCoord();

    int gt[3][3];
    int r,coordi,coordj;

    void initiate()
    {
        for(int i=0;i<=3;i++)
            for(int j=0;j<=3;j++)
                gt[i][j]=0;
        random();
    //  randomCoord();
    //  gt[coordi][coordj]=r;
    //  randomN();
    //  randomCoord();
    //  gt[coordi][coordj]=r;
        for(int i=0;i<=3;i++)
        {
            cout<<endl;
            for(int j=0;j<=3;j++)
                cout<<gt[i][j]<<" ";
        }
    }

    void random()
    {
        srand (time(NULL));
        do
            {
                r = rand() % 4 + 2;
                if(r==2 || r==4)
                    break;
            }
        while(1);
    }
    void randomCoord()
    {
        srand (time(NULL));
        coordi = rand() % 4;
        coordj = rand() % 4;
    }

    int main()
    {
        initiate();

        return 0;
    }

I am expecting that when I print the matrix on the screen to get a matrix full of zero...but for some reason the values gt[2][3] and gt[3][0] get the value of r. I don't understand the reason why.

Thanks for help!

max66
  • 65,235
  • 10
  • 71
  • 111
Smoke HHH
  • 83
  • 9
  • Please have a look at https://stackoverflow.com/questions/30631020/why-can-i-set-values-outside-of-the-arrays-range (especially the first two answers) – 0x01 Mar 13 '18 at 20:24

1 Answers1

1

If you want to write in gt[2][3] and gt[3][0], your gt must be

int gt[4][4];

If your gt is gt[3][3], when you access in position 3 (for first or second index) you are (as far I know) in Undefined Behavior.

max66
  • 65,235
  • 10
  • 71
  • 111