Function auto-assigns values in my matrix

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!

1 answer

  • answered 2018-03-13 20:15 max66

    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.