Jonn Ralge Yuvallos
Jonn Ralge Yuvallos

Reputation: 23

Tried to create a simple map where the player can move around, failed miserably

So whenever I run this code I end up with a screen full of random symbols, and when I try to move the player the program crashes. I've been stuck for quite a while trying to solve it and any insights would be extremely appreciated.

#include <stdio.h>
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 one value to everything in the board
        for(y = 0; y < size; y++)
        {
            map[size][size] = 'X';
        }
    }
while(test != 0)
{
    scanf("%d", &test); //just so I can keep testing over and over
    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");
    }
    printf("Use W, A, S, D to move around.");
    scanf(" %c", move);
    map[row][col] = 'X'; //set the old player location to the original value.
    switch(move)
    {
        case 'w': 
        case 'W': row -= 1; break;
        case 's':
        case 'S': row += 1; break;
        case 'a':
        case 'A': col -= 1; break;
        case 'd':
        case 'D': col += 1; break;
    }
    map[row][col] = 'O';
}
return 0;
}

Upvotes: 0

Views: 164

Answers (1)

Dave X
Dave X

Reputation: 5137

        map[size][size] = 'X';

should probably be

        map[x][y] = 'X';

and

            map[row][col] = 'O';

should be

            map[x][y] = 'O';

Also, protect row and col from getting outside of [0,size]

... Also, change

scanf(" %c", move);

to

scanf(" %c", &move);

Writing characters to to whatever the existing value of move points to is causing the crash.

Upvotes: 1

Related Questions