[英]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()
: 尝试move
的地址提供给scanf()
:
scanf(" %c", &move);
scanf()
needs a destination (address) specifying where to write the character scanned/read. scanf()
需要一个目的地 (地址),用于指定在何处写入已扫描/读取的字符。 You are giving it whatever garbage value happens to be in move
. 您给它的是垃圾值是否在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. ,忘记&
使用scanf
是C编程中最常见的错误之一。
And you forgot &
for move
in scanf
. 你忘了&
用于move
在scanf
。
Look into your code, I believe that you have already known the reason why need to pass address to scanf
查看您的代码,我相信您已经知道了为什么需要将地址传递给scanf
的原因
But in case you haven't, you could refer this with high quality accepted answer Why scanf must take the address of operator 但是,如果没有,您可以参考高质量的可接受答案, 为什么scanf必须使用运算符的地址
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.