简体   繁体   中英

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

Try giving the address of move to scanf() :

scanf(" %c", &move);

scanf() needs a destination (address) specifying where to write the character scanned/read. You are giving it whatever garbage value happens to be in move . It is using this value as an address and trying to write your character there. Since it is writing to an invalid memory location, it crashes.

Like forgetting ; , forgetting & in scanf is one of the most common mistakes in C programming.

And you forgot & for move in scanf .

Look into your code, I believe that you have already known the reason why need to pass address to scanf

But in case you haven't, you could refer this with high quality accepted answer Why scanf must take the address of operator

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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