繁体   English   中英

关于在 c 程序中使用动态分配的二维数组的问题

[英]problem about using a dynamically allocated 2d array in a c program

我在进行 9 x 9 井字游戏程序时遇到问题。

当我输入诸如 (5,5) 之类的坐标时,x 会正确显示在网格上。

我的问题是,当我输入一个包含数字 7 的坐标时,例如 (4,7),网格上会显示两个 X。

我之前做过程序,将我的数组声明为全局变量。 一切正常。 当我切换到动态分配的数组并使用双指针传递数组时,问题就开始了。 所以我猜我的问题是因为我的数组。 有人可以告诉我这个问题发生在哪里以及如何解决它。

我已经在我的 main 中声明了数组

//previously the array was declared here
//char grid[ROW][COLUMN];

int main() 
{
    //dynamically create an array of pointers os size ROW
    char **grid = (char **)malloc(ROW * sizeof(char *));

    // dynamically allocate memory of size ROW*COLUMN and let *grid point to it
    *grid = (char *)malloc(sizeof(char) * ROW * COLUMN);

移动方法

int make_move(char **grid, int x, int y,int row, int col, char letter) 
{
    if (x < 0 || x >= row || y < 0 || y >= col || grid[x][y] != ' ' )
    { 
        // checks to see if the input is valid
        return 1;
    }
    if( grid[x][y] == ' ')
    grid[x][y] = letter; 
    // sets the coordinates in the grid to the letter
    return 0;
}

更新网格方法


// Updates the grid accordingly every time a move is made
void update_grid(char **grid,int x, int y, int row, int col)
{
   // int counter = 1;

    //checks the input
    while  (x < 0 || x >= row || y < 0 || y >= col || grid[x][y] != ' ')
    {
        fputs("Error, Move not valid! Please reenter: ", stderr);
    scanf("%d,%d", &x, &y);
    }



    ++counter; 
    { 
        //Acts as an increment for the turns of the players
        if(counter % 2 == 0)
        { 
            //checks to see if it is player X's turn
        grid[x][y] = 'X';
        }
        if(counter % 2 != 0)
        {  
            //checks to see if it is player O's turn
            grid[x][y] = 'O';
        }

//prints grid

        printf(" ");
        for (int c = 0; c < col; c++) 
        {
            printf(" ");
        printf(" %d", c);
        }
        printf("\n");

        for (int r = 0; r < row; ++r) 
        {
            printf("%d", r);
            printf("|");
        for (int dot = 0; dot < (col*row); ++dot) 
            {

            printf("|");
            printf("%c", grid[r][dot]);
            printf(" ");

            if (dot == col - 1) 
                { 
                    // stops j from over printing
                printf("|| \n");
                break;
            }
            }
        }
    }
}

B. Go 说您的 malloc 是错误的,这就是它的外观。

//dynamically create an array of pointers os size ROW
char **grid = malloc(ROW * sizeof(char *));

for(size_t i = 0; i < ROW; i++){
    grid[i] = malloc(COLUMN);
}

您分配了ROW指针,但只填充了第一个指针,您需要为它们提供每个COLUMN字节的数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM