0

私たちの c コースでは、先生から「リバーシ」ゲームを作成するためのミニ プロジェクトが与えられました。板を作るのに苦労しました。

#define Size 8
int main()
{
    char Board[Size][Size] = { {" "} };
    resetBoard(Board);
    printBoard(Board);
    printf("\n");
    getch();
}
void resetBoard(int** board)
{
    for (size_t i = 0; i < Size; i++)
    {
        for (size_t j = 0; j < Size; j++)
        {
            *(board + (i * Size + j)) = 'x';
        }
    }
}
void printBoard(int board[Size][Size])
{
    for (size_t i = 0; i < Size; i++)
    {
        for (size_t j = 0; j < Size; j++)
        {
            printf("%c", board[i][j]);
            printf(" ");
        }
        printf("\n");
    }
}

プログラムをチェックしたところ、プログラムは次のようになりました。

実行時チェックの失敗 #2 - 変数 'Board' の周りのスタックが壊れていた

3行目の最初のXを変更したとき。たとえば、2 番目の行 (16) の終わりまでプログラムを実行すると、このエラーは発生しません。

4

4 に答える 4

1

コードに大量のエラーが発生しました。インライン コメントを参照してください。

    //Use all capitals for defines
#define BOARD_SIZE 8

//Just reset the whole array to spaces.. No need to traverse byte by byte.
void resetBoard(char* board) {
    //memset version
    //memset(board, ' ', (BOARD_SIZE*BOARD_SIZE)*sizeof(char));

    //non memset version
    for (int i=0; i<(BOARD_SIZE*BOARD_SIZE); i++) *board++='x';
}

void printBoard(char *board) {
    for (int i = 0; i < BOARD_SIZE; i++){
        for (int j = 0; j < BOARD_SIZE; j++){
            //Access the 2D array like this (y * width of array + x)
            printf("%c", board[i*BOARD_SIZE+j]);
            printf(" ");
        }
        printf("\n");
    }
}

//Don't start a name using capitals.. Later when you program c++ or similar you will understand :-)
int main()
{
    //This is a more dynamic memory model and is not allocated on the stack.. (free when done!!)
    char *board=(char*)malloc(BOARD_SIZE*BOARD_SIZE);
    //there are several ways of working with arrays.. No need to complicate stuff if not needed.
    //Just point out the first byte of the array.. (See the methods takes a char pointer and that is what's passed the methods)
    if (board) {
        resetBoard(board);
        //Test to see if it works
        board[1*BOARD_SIZE+2]='0';
        printBoard(board);
        free(board);
    } else {
        printf("Out of memory!\n");
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

または、2020 年のように見せびらかすこともできます。

#define B 16 //Define the size of the 2d matrix
void printMatrix(char*b){for(int i=-1;i<B*B-1;(++i+1)%B?printf("%c ",b[i%B*B+i/B]):printf("%c\n",b[i%B*B+i/B])){}} //Print the 2d matrix
int main(){
    char b[B*B]={[0 ...B*B-1]='x'}; //Reserve the 2d matrix space and set all entries to 'x'
    printMatrix(&b[0]); //pass the pointer to the print 2d matrix method
    return 0; //Done!
}

または 2021 ;-) (2 次元配列)

#define B 32
void p(char b[B][B]){for(int i=-1;i<B*B-1;(++i+1)%B?printf("%c ",b[i%B][i/B]):printf("%c\n",b[i%B][i/B])){}}
int main(){
    char b[B][B]={[0 ...B-1][0 ...B-1]='x'};
    p(&b[0]);
}
于 2018-11-28T19:11:50.033 に答える