不相关循环的0破坏逻辑的二维数组- C++

列出的代码来自我正在处理的一个较大的项目(我删除了本文不需要的几乎所有其他内容),该项目在正常运行时遇到了一些问题。我找到了导致错误的那行代码,但我希望能得到关于这行代码导致错误的原因的解释。

#include <iostream>
#include <tgmath.h>

using namespace std;

int main() {
  const int m = 2;    //  Number of rows
  const int n = 2;    //  Number of cols

  int totalPoss = 0;  //  Number of unique possibile m X n binary matrices

  //  2^(m * n) = the number of unique binary
  //  combinations of m X n matrices
  int stop = pow(2, m * n);

  //  Error when a = 0, 1 | m = 0 | n = 1
  for (int a = 0; a < stop; a++) {
    int poss[m][n] = {0};       //  2D Array to store each possible matrix
    int nextGen[m][n] = {0};    //  2D Array to store the next generation of cells
    int rem[m * n];             //  1D Array to store the binary entries of the poss[m][n]

    totalPoss = a;
    int hold = a;           //  Stores the current "possibility number" (i.e when
                            //  a = hold = 1 the binary equivilent of 1 will be stored
                            //  in rem[m * n])

    //  Generate binary number based on whatever a is at current iteration
    int c = 0;
    while (hold > 0) {

      // storing remainder in binary array
      rem[c] = hold % 2;
      hold = hold / 2;
      c++;
    }

    cout << "Binary: ";
    for (int i = 0; i < (m * n); i++) {
      cout << rem[i] << " ";
    }

    cout << endl << endl;
  }

  cout << "Total possibilities: " << totalPoss+1 << endl;

  return 0;
}

有问题的行是第19行,或int nextGen[m][n] = {0};。此状态下程序的目的是输出所有可能的4位唯一二进制数。要转换为二进制的数字由初始for循环确定。该数字在while循环中转换并存储在rem[m][n]中。这段代码运行良好,除非包含第19行。无论出于什么原因,当创建这个二维数组时,0和1的输出是1 14 0 0,但2-15的输出是正确的。我的问题是,为什么这一行(看似不相关)会破坏我的代码。

谢谢!

转载请注明出处:http://www.xgclsm.com/article/20230526/1527494.html