以下代码存在段错误问题(也已发布at pastebin):
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include "mygetch.h"
#define MAX_SIZE 255
#define SCR_CLEAR "\033[2J\033[;H"
void getgrid(int, int);
void resetgrid(void);
void getkey(void);
static bool grid[5][5] = {{0,0,0,0,0},
{0,0,0,0,0},
{0,0,0,0,0},
{0,0,0,0,0},
{0,0,0,0,0}};
int main() {
while(1) {
getkey();
}
return 0;
}
void getgrid(int xpos, int ypos) {
int x = 0;
int y = 0;
grid[xpos][ypos] = 1;
for(x = 0; x <= 4; x++) {
for(y = 0; y <= 4; y++) {
printf("%i ", grid[x][y]);
}
printf("\n");
}
}
void resetgrid() {
int x = 0;
int y = 0;
for(x = 0; x <= 4; x++) {
for(y = 0; y <= 4; y++) {
grid[x][y] = 0;
}
}
}
void getkey() {
static int xpos = 0;
static int ypos = 0;
int c = mygetch();
//0x41 = up.. apparently on my linux console?
//0x42 = down
//0x44 = left
//0x43 = right
if(c == 0x41 && ypos != 0) {
ypos--;
} else if(c == 0x42 && ypos != 4) {
ypos++;
} else if(c == 0x44 && xpos != 4) {
xpos--;
} else if(c == 0x43 && xpos != 0) {
xpos++;
}
resetgrid();
printf(SCR_CLEAR);
getgrid(xpos, ypos);
}
你可以假设mygetch()
返回一个ASCII整数代码点,在我的linux控制台上上下左右是A/B/C/D,所以我这样映射它们。
我的问题是由于某种原因,即使我正确定义了多维数组,当我按上/下/左/右左和右不起作用时,它们会离开屏幕并导致段错误,现在我知道按键了映射正确,所以我不知道为什么 y--
y++
等将无法正确运行,除非我在定义数组或其他地方出错。
我肯定会从解决这个问题和做更多事情中学到很多东西,但这只是我想做的一件有趣的事情。
最佳答案
左和右的边界条件是相反的。你应该有:
if (c == 0x41 && ypos != 0) {
ypos--;
} else if(c == 0x42 && ypos != 4) {
ypos++;
} else if(c == 0x44 && xpos != 0) {
xpos--;
} else if(c == 0x43 && xpos != 4) {
xpos++;
}
而不是:
if (c == 0x41 && ypos != 0) {
ypos--;
} else if(c == 0x42 && ypos != 4) {
ypos++;
} else if(c == 0x44 && xpos != 4) {
xpos--;
} else if(c == 0x43 && xpos != 0) {
xpos++;
}
关于c - 使用 getch 在 C 中进行简单游戏 - 段错误问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4103920/