我正在研究 Conway 的生命游戏,但我的数组有问题。我可以将二维数组一次传递给评估当前世界的函数。结果像他们应该的那样回来。然后当再次通过时,我得到各种垃圾。我认为这与内存有关,但我不确定如何解决它。
0 0 0 0 0
0 0 1 0 0
0 0 1 0 0
0 0 1 0 0
0 0 0 0 0
变成
0 0 0 0 0
0 0 0 0 0
0 1 1 1 0
0 0 0 0 0
0 0 0 0 0
但如果它第二次通过,我的结果就会变得疯狂
1946813184 32767 1946813184 32767 1946812520
32767 1946813184 1 1411353440 32767
-1983101020 0 1 0 1411353160
32767 1946813184 1 1946815600 32767
1 0 1946813176 32767 1946815600
这是我的代码
#include <iostream>
#include <string>
#include <ctype.h>
#include <cstring>
#include <stdlib.h>
using std::cout;
using std::cin;
using std::endl;
using std::string;
void updateWorld(int world[][5], int x, int y);
int choice();
int main() {
int world[5][5] = {{ 0, 0, 0, 0, 0},
{ 0, 0, 1, 0, 0},
{ 0, 0, 1, 0, 0},
{ 0, 0, 1, 0, 0},
{ 0, 0, 0, 0, 0}};
updateWorld(world, 5, 5); //Call function first time
for (int i = 0; i < 5; i++) { //print array
cout << endl;
for (int j = 0; j < 5; j++) {
cout << world[i][j] << " ";
}
}
updateWorld(world, 5, 5); //Call function second time
for (int i = 0; i < 5; i++) { //print array
cout << endl;
for (int j = 0; j < 5; j++) {
cout << world[i][j] << " ";
}
}
return 0;
}
bool validNum(string str) {
bool valid = true;
for (int i = 0; i < str.length() && valid == true; i++) {
valid = isdigit(str.at(i));
}
return valid;
}
void updateWorld(int worldi[][5], int x, int y) {
int worldo[5][5];
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) { //counts through all the cells
int life = 0; // keeps track of the life around the cell
for (int a = -1; a < 2; a++) {
for (int b = -1; b < 2; b++) { //these two loops check every neighbor cell
int c = a;
int d = b;
if (i+a < 0) {
c = x;
} else if (i + a > x-1) {
c = 0;
} else {
c = i + a;
}
if (j+b < 0) {
d = y;
} else if (j+b > y-1){
d = 0;
} else {
d = j + b;
}
if (worldi[c][d] == 1) {
life++;
// << ":" << life << endl;
} // cout << c << "," << d << ":" << life << endl;
}
}
life = life - worldi[i][j]; // subtract the cells self value
if (worldi[i][j] == 1 && life < 2) { // implent the 4 rules
worldo[i][j] = 0;
} else if (worldi[i][j] == 1 && 1 < life && life < 4) {
worldo[i][j] = 1;
} else if (worldi[i][j] == 1 && life > 3) {
worldo[i][j] = 0;
} else if (worldi[i][j] == 0 && life == 3) {
worldo[i][j] = 1;
}
}
}
for (int i = 0; i < x; i++) { //set the input arrary to the temp output array
for (int j = 0; j < y; j++) {
worldi[i][j] = worldo[i][j];
}
}
}
最佳答案
您忘记在 updateWorld
中初始化 worldo
。更改行:
int worldo[5][5];
到
int worldo[5][5] = {0};
关于c++ - 在 C++ 函数中多次使用数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25346352/