c++ - 为什么这个变量被设置为假?

标签 c++ boolean

我有一个函数可以检查数独板上某个坐标的可能答案。不过,我只需要您先关注变量。出于某种原因,first 设置为 false,我不知道为什么。

功能:

void displayPossible(int board[][9], char input[], int &row, int &col)
{
  bool first = true;                          // variable instantiated and set to true
  cout << "First " << first << endl;

  bool possible[9];                           // I dont touch `first` at all
  computeValues(board, possible, row, col);   // between these two lines..

  cout << "First " << first << endl;          // by this point it is false. WHY!?
  cout << endl;

  cout << "Possible: ";
  for(int i = 0; i < 9; i++)
    cout << possible[i];
  cout << endl;

  cout << "First " << first << endl;
  cout << "The possible values for '" << input << "' are: ";
  // if I say 'first = true' right here, i get my expected outcome
  for(int i = 0; i < 9; i++)
    {
      if(possible[i] && first == true)
        {
          first = false;
          cout << i;
        }
      else if(possible[i] && first == false)
        cout << ", " << i;

      else
        ;
    }
  cout << endl;
}

输出:

First 1
First 0

Possible: 000010001
First 0
The possible values for 'd1' are: , 4, 8

计算值:

void computeValues(int board[][9], bool possible[], int row, int col)
{
  for(int i = 0; i < 9; i++)
    possible[i] = true;

  for(int iRow = 0; iRow < 9; iRow++)
    possible[board[iRow][col]] = false;

  for(int iCol = 0; iCol < 9; iCol++)
    possible[board[row][iCol]] = false;

  for(int iRow = 0; iRow < 2; iRow++)
    for(int iCol = 0; iCol < 2; iCol++)
      possible[board[row/3*3 + iRow][col/3*3 + iCol]] = false;

  if(board[row][col] != 0)
    possible[board[row][col]] = true;
}

最佳答案

很可能是 computeValues 有一个缓冲区溢出,它破坏了 first 的值。一种明显的可能性是它写入 possible 时索引越界。由于 possiblecomputeValues 很可能在堆栈中彼此相邻,这似乎是一个可能的解释。

关于c++ - 为什么这个变量被设置为假?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8416585/

相关文章:

c# - boolean 状态未能阻止功能重复

c++ - 将 bool 值传递给另一个函数无法正常工作?

f# - 无法在 F# 中重载 boolean 运算符

c++ - std::lower_bound 跳过无效元素

c++ - 不执行参数化基类构造函数就存在中间类

python - 如何在 Pandas 数据框中有效地查找交替 boolean 值的索引

java - 比较 boolean 值

c++ - 如何在 C++ 中遍历一个类型的每一位

c++ - Kd-Tree 有缺陷的 K 最近邻

c++ - 类中的while循环不会执行c++