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;
}
Asked
Active
Viewed 51 times
0

John Hascall
- 9,176
- 6
- 48
- 72

Jonn Ralge Yuvallos
- 23
- 5
2 Answers
3
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.

e0k
- 6,961
- 2
- 23
- 30
2
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