簡體   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