c - 有没有更好的方法来确保矩阵之外的元素不被访问?

标签 c performance matrix multidimensional-array segmentation-fault

我正在使用 Ncurses 库用 C 语言编写游戏跳棋程序,并且我将所有棋子存储在矩阵、g.board 中,并且在寻找可能的移动时,我需要确保程序不会尝试访问由于分割错误,元素位于矩阵之外。我有一个解决方案,但感觉相当粗糙,我感觉有一种更优雅的方法可以做到这一点,但我找不到或想到它。

int xint y引用该矩阵中的 x 和 y 位置,我想在该矩阵中寻找可能的移动。 char ck只是告诉我,如果这件作品是一种颜色的国王,那么正常的颜色只能向一个方向移动。 g.board[y][x].possible只是结构中的 bool 变量告诉我这是否是可能的移动。

void checkPossible(int y, int x, char ck);
{
    bool left = false, right = false, top = false, bottem = false;

    // Dertimes if a tile is out of bounds 
    if (y != 0)
    {
        top = true;        
    }
    if (y != 8)
    {
        bottem = true;
    }
    if (x != 0)
    }
        left = true;
    }
    if (x != 8)
    {
        right = true;
    {

    // Sets g.board.possible to true if possible move
    if ((top == true && left == true) && (ck == 'k' || ck == 'w'))
    {
        g.board[y - 1][x - 1].possible = true; 
    }
    if ((top == true && right == true) && (ck == 'k' || ck == 'w'))
    {
        g.board[y - 1][x + 1].possible = true; 
    }
    if ((bottem == true && left == true) && (ck == 'k' || ck == 'r'))
    {
        g.board[y + 1][x - 1].possible = true; 
    }
    if ((bottem == true && right == true) && (ck == 'k' || ck == 'r'))
    {
        g.board[y + 1][x + 1].possible = true; 
    }
}

据我所知它有效,我没有对其进行太多测试,但感觉很粗糙。 对于任何错误或不太理想的编码,我深表歉意,我对此很陌生。

最佳答案

有一件事看起来很可疑。 g.board[y - 1][x - 1].possible == true 应该是 g.board[y - 1][x - 1].possible = true >。当前代码不执行任何操作。

代码也非常复杂。看看这个:

void checkPossible(int y, int x, char ck);
{
    bool left = x != 0, 
         right = x != 8, 
         top = y !=8, 
         bottem = y!=0;

    // Sets g.board.possible to true if possible move
    if(ck == 'k' || ck == 'w') {
        g.board[y - 1][x - 1].possible = (top && left);
        g.board[y - 1][x + 1].possible = (top && right);
        g.board[y + 1][x - 1].possible = (bottem && left);
        g.board[y + 1][x + 1].possible = (bottem && right);
    }
}

一般情况下,不要将 bool 变量与 bool 常量 true 和 false 或其他值进行比较。直接按原样使用它们,并为它们指定描述性名称。

另外,我会(可能是因为我还没有看到代码的其余部分)对坐标和字符进行分开检查。在单个函数中放置的功能越少,它就越容易理解、维护和命名。像这样:

bool isValidCoordinate(int y, int x) {
    return y>=0 && y<=8 && x>=0 && x<=8;
}

bool isValidCharacter(char ck) {
    return ck == 'k' || ck == 'w';
}

我不知道这是否适合您的项目,但它提供了您如何做到这一点的想法。

关于c - 有没有更好的方法来确保矩阵之外的元素不被访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55946497/

相关文章:

python - 在 Python 中使用 Redis 将数据保存在内存中的最快方法

c++ - float 与 int 比较需要额外的时间吗?

mySQL/Server 性能检查.. 1000 个基本更新查询 = QuadCore i7 设备上的 57 秒.. 好还是坏?

R 对 n 列中的每 n 行求和

java - 如何使用表格格式打印实数矩阵

clojure - Clojure 中的科学数据集操作——将 ByteBuffers 读入矩阵

c - 在 C 中如何检查输入不是 int 或 float ?

c - 如何声明和初始化指向char指针数组的指针数组?

c - 输入双关语 : int[] and struct { int … }

c - 我的 For-Loop 无法工作,但没有引发错误消息 - 可能是什么?