函数在我的矩阵中自动分配值

Function auto-assigns values in my matrix

本文关键字:分配 我的 函数      更新时间:2023-10-16

我正在尝试制作像2048这样的游戏,但我遇到了一个问题。

    #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;
    }

我希望当我在屏幕上打印矩阵以获得充满零的矩阵时......但是由于某种原因,这些值gt[2][3]gt[3][0]得到r的值。我不明白原因。

感谢您的帮助!

如果你想用gt[2][3]gt[3][0]写,你的gt必须是

int gt[4][4];

如果您的gtgt[3][3],当您在位置3(对于第一个或第二个索引(访问时,您(据我所知(处于未定义行为状态。