![](/img/trans.png)
[英]My program crashes when I try to read a NULL value using sqlite in 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编程中最常见的错误之一。
你忘了&
用于move
在scanf
。
查看您的代码,我相信您已经知道了为什么需要将地址传递给scanf
的原因
但是,如果没有,您可以参考高质量的可接受答案, 为什么scanf必须使用运算符的地址
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.