自作のcount関数でセグメントエラーが起こっているようです。
このコードは30*30のマスに0か1の値が割り振られていて、1のマスの座標情報を書き出し、
ルールにのっとってマスの値を変えるというのを150回繰り返すものです。
count関数で周りのマスの値が1のものをカウントし、その個数によってあるマスの次のターンの値が決まります。
if文で存在しない配列にアクセスしないように気を付けているのですが、不十分でしょうか?
ご教授お願いいたします。
#include<stdio.h>
#define xgrid 30
#define ygrid 30
int count(int data[xgrid][ygrid]) {
int x, y, check;
check = 0;
if (x > 0 && y < (ygrid - 1)) {
if (data[x - 1][y + 1] == 1) {
check += 1;
}
}
if (x > 0 && y > 0) {
if (data[x - 1][y - 1] == 1) {
check += 1;
}
}
if (x > 0) {
if (data[x - 1][y] == 1) {
check += 1;
}
}
if (y > 0 && x < (xgrid - 1)) {
if (data[x + 1][y - 1] == 1) {
check += 1;
}
}
if (y < (ygrid - 1) && x < (xgrid - 1)) {
if (data[x + 1][y + 1] == 1) {
check += 1;
}
}
if (x < (xgrid - 1)) {
if (data[x + 1][y] == 1) {
check += 1;
}
}
if (y < (ygrid - 1)) {
if (data[x][y + 1] == 1) {
check += 1;
}
}
if (y > 0) {
if (data[x][y - 1] == 1) {
check += 1;
}
}
return check;
}
int main(void) {
int data[xgrid][ygrid];
int i, x, y, check;
for(x = 0; x < xgrid; x++) {
for(y = 0; y < ygrid; y++) {
data[x][y] = 0;
}
}
data[11][8] = data[15][8] = data[16][8] = data[17][8]
= data[10][7] = data[11][7] = data[16][6] = 1;
for(i = 0; i < 151; i++) {
for(x = 0; x < xgrid; x++) {
for(y = 0; y < ygrid; y++) {
if (data[x][y] == 0) {
check = count(data);
if (check == 3) {
data[x][y] = 1;
} else {
printf("%d %d\n", x + 1, y + 1);
check = count(data);
if (check < 2 || check > 3) {
data[x][y] = 0;
}
}
}
}
}
printf("-1 -1\n\n\n");
}
return 0;
}