c - 使用 getch 在 C 中进行简单游戏 - 段错误问题?

标签 c arrays segmentation-fault

以下代码存在段错误问题(也已发布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/

相关文章:

c++ - 如果他们定义了标准 ABI,C/C++ "lose"会是什么?

vs2010 c 找不到 dll

arrays - 在mongodb中更新数组中的多个元素

c++ - C++线程中的段错误

我们可以使用 open CV 和 C 来锁定 ubuntu 中的文件或文件夹吗

c - 将十六进制写入 C 文件(不是 ASCII)

JavaScript - 循环数组比我应该的少

ios - 使用 swift 在文本字段中列出核心数据属性

c - C 中的段错误,可能在中型/大型动态分配的数组上

c - 尝试在 MPI 中通过多个等级发送一个循环数组,但出现段错误。谁能告诉我为什么吗?