簡體   English   中英

當我嘗試在C中的簡單地圖上跨屏幕移動播放器時,程序崩潰

[英]Program crashes when I try to move my player across the screen on a simple map in C

    int main()
    {
        int size, x, y, test = 1;
        printf("How big is your map? ");
        scanf("%d", &size);
        char map[size][size], move;
        int row = size/2, col = size/2;
        for(x = 0; x < size; x++)
        { //gives null value to everything in the board except for the player
            for(y = 0; y < size; y++)
            {
                map[x][y] = 'X';
            }
        }
        while(test != 0)
        {
            scanf("%d", &test);
            for(x = 0; x < size; x++)
            {
                for(y = 0; y < size; y++)
                    if (x == row && y == col)
                    {
                        printf("O");
                        map[row][col] = 'O';
                    }
                    else
                        printf("%c", map[x][y]);
                    printf("\n");
            }
//
// Everything runs completely fine until this point,
// after I type either W, A, S, or D, the program crashes
// and gives me an insanely high return value.
// I have no idea what I did wrong, and any insight would be extremely appreciated.
//
            printf("Use W, A, S, D to move around.");
            map[row][col] = 'X'; //set the old player location to null.
            while(x != 0)
            {
                scanf(" %c", move);
                switch(move)
                {
                    case 'w': 
                    case 'W': row -= 1; x = 0; break;
                    case 's':
                    case 'S': row += 1; x = 0; break;
                    case 'a':
                    case 'A': col -= 1; x = 0; break;
                    case 'd':
                    case 'D': col += 1; x = 0; break;
                    default: printf("Invalid input, try again.");
                }
            }
            map[row][col] = 'O';
        }
        return 0;
    }

嘗試move地址提供給scanf()

scanf(" %c", &move);

scanf()需要一個目的地 (地址),用於指定在何處寫入已掃描/讀取的字符。 您給它的是垃圾值是否在move 它使用此值作為地址並嘗試在其中寫入您的字符。 由於它正在寫入無效的內存位置,因此會崩潰。

喜歡忘記; ,忘記&使用scanf是C編程中最常見的錯誤之一。

你忘了&用於movescanf

查看您的代碼,我相信您已經知道了為什么需要將地址傳遞給scanf的原因

但是,如果沒有,您可以參考高質量的可接受答案, 為什么scanf必須使用運算符的地址

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM