#include "Cell.h"
#include <iostream>
using namespace std;
void Cell::CreateArea(int x[][100], int y[][100], int f, int c, int tc){
int f1, c1;
for (int i = -1; i <= f; i++){
for (int j = -1; j <= c; j++){
x[i][j] = 0;
y[i][j] = 0;
}
}
//Copy(y,x,f,c); //copy the matrix of zeros in another temporary array
while (tc){
bool re = true;
while (re){
f1 = rand() % f;
c1 = rand() % f;
if (x[f1][c1] == 0)
{
x[f1][c1] = 1; //enter random cells in random positions that are not repeated
re = false;
}
}
tc--; //decreases the umber of cells to be entered
}
}
void Cell::PrintArea(int x[][100], int f, int c){
for (int i = 0; i<f; i++){
for (int j = 0; j<c; j++){
if (x[i][j] == 1) cout << '*'; //Prints a "*" if cells are alive
else cout << '.'; //Prints a "." if cells are dead
}
cout << endl;
}
}
int Cell::Population(int x[][100], int f, int c){
int counter = 0;
for (int i = 0; i<f; i++)
for (int j = 0; j<c; j++)
if (x[i][j] == 1)counter++;
return counter;
}
当我运行此代码时,它可以工作,但在它执行后它崩溃给我错误: C ++ AssignmentPart1.exe中0x00D64674处的未处理异常:0xC0000005:访问冲突写入位置0xFFFFFE88。
有人知道为什么请吗?你已经在这几个小时!
答案 0 :(得分:2)
数组从0
转到n-1
,因此CreateArea
循环不正确:
for (int i = -1; i <= f; i++){
for (int j = -1; j <= c; j++){
-1不是有效的数组索引!你必须从0到f或c。如果它们从零开始,很可能排除f和c(人们经常做的数组索引从0到99):
for (int i = 0; i < f; i++){
for (int j = 0; j < c; j++){
同时检查功能开始时f和c是否低于100!然后,你确定你永远不会写出数组边界......