c - 传递给函数的值与接收到的值不同

标签 c

我正在创建一个程序来解决数独,其中包含每个单元格的结构,其中包含单元格的值以及单元格的所有可能值(作为 int),每个位对应于一个可能的值。

为了更新每个单元格,我有一个名为 applyMask 的函数,该函数从受该单元格影响的所有其他单元格中删除与该单元格编号相对应的位。该函数在测试中工作正常,但是当我循环所有单元格时,会传递大量数字而不是正确的数字。例如,它将正确地传递 x is 0 和 y is 2,但接下来它不会传递 x is 0 和 y is 3,而是传递 x is 4199111 和 y is 1。在 gdb 中,函数传递 x is 0 和 y是 3,但是进入该函数后,它显示 x 是 4199111,y 是 1。该函数调用:

typedef struct Cell
{   int values;
    int value;
} cell;

void getSection(int pos, int *section1, int *section2)
{   switch(pos % 3){
    case 0:
        *section1 = pos + 1;
        *section2 = pos + 2;
    case 1:
        *section1 = pos - 1;
        *section2 = pos + 1;
    case 2:
        *section1 = pos - 2;
        *section2 = pos - 1;
    }
}

void applyMask(cell sudokuBoard[9][9], int x, int y)
{   int mask = ~(1<<(sudokuBoard[x][y].value-1));

    for(int maskP = 0; maskP < 9; maskP++)
    {   sudokuBoard[maskP][y].values &= mask;
        sudokuBoard[x][maskP].values &= mask;
    }

    int sectionX1;
    int sectionX2;
    getSection(x, &sectionX1, &sectionX2);
    int sectionY1;
    int sectionY2;
    getSection(y, &sectionY1, &sectionY2);

    sudokuBoard[sectionX1][sectionY1].values &= mask;
    sudokuBoard[sectionX1][sectionY2].values &= mask;
    sudokuBoard[sectionX2][sectionY1].values &= mask;
    sudokuBoard[sectionX2][sectionY2].values &= mask;
}

并且被调用

for(int i = 0; i < 9; i++)
    for(int j = 0; j < 9; j++)
        applyMask(sudokuBoard, i, j);

最佳答案

您熟悉关键字 break 及其在 switch()case 部分中的使用吗?

这个:

switch(pos % 3){
 case 0:
     *section1 = pos + 1;
     *section2 = pos + 2;
 case 1:
     *section1 = pos - 1;
     *section2 = pos + 1;
 case 2:
     *section1 = pos - 2;
     *section2 = pos - 1;
 }

将始终执行所有 case:s 代码,因为它们中没有 break。这被称为“失败”行为,并且在有意的情况下会非常方便。

您应该添加break,所以它看起来像这样:

switch(pos % 3){
case 0:
    *section1 = pos + 1;
    *section2 = pos + 2;
    break;
case 1:
    *section1 = pos - 1;
    *section2 = pos + 1;
    break;
case 2:
    *section1 = pos - 2;
    *section2 = pos - 1;
}

关于c - 传递给函数的值与接收到的值不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53014543/

相关文章:

c - 此方法是否返回 int Nrows 和 int Ncols?

c - Makefile 可执行文件错误

C指针指向指针警告

c - OpenGL - 使用锥形聚光灯创建平面

c++ - 使用 realloc() 使 memmove() 安全

计算 CFStringRef/CFMutableArrayRef 使用的字节数

c - Eratosthenes 算法筛法 - 工作正常但在之后崩溃

c++ - 什么是#pragma weak_import?

c++ - 查找目录中所有 .cpp .h 文件的常规方法(include、src 等...)

c++ - 使用 strlen 时不为空终止符添加 +1 会导致在使用 send 时发送额外的垃圾字节