Crocus Crocus - 1 month ago 6
C Question

Check status of neighbors in recreation of Game of Life in C

I've got an assignment to recreate Conway's Game Of Life in C. In the following code I'm trying to check if the neighbors to a given coordinate in a 2D-array has the status DEAD or ALIVE:

int checkNeighbor(int i, int j, cell field[i][j]) {
int sum=0;


if(canGoUp(i) && canGoLeft(j) && (field[i-1][j-1].current == ALIVE)) {
sum++;
}
if(canGoUp(i) && (field[i-1][j].current == ALIVE)) {
sum++;
}
if(canGoUp(i) && canGoRight(j) && (field[i-1][j+1].current == ALIVE)) {
sum++;
}
if(canGoRight(j) && (field[i][j+1].current == ALIVE)) {
sum++;
}
if(canGoDown(i) && canGoRight(j) && (field[i+1][j+1].current == ALIVE)) {
sum++;
}
if(canGoDown(i) && (field[i+1][j].current == ALIVE)) {
sum++;
}
if(canGoDown(i) && canGoLeft(j) && (field[i+1][j-1].current == ALIVE)) {
sum++;
}
if(canGoLeft(j) && (field[i][j-1].current == ALIVE)) {
sum++;
}

return sum;
}


The functions named "canGoUP" or "canGoDown" etc prevents segfaults by checking if the coordinate is near the edge of the 2D-array. Now, For some reason the code is not working nearly perfect. I get some indications of neighbors but it almost never tells me the right amount. Is there a better way to go about the problem? or have I just missed something in the code?

Answer

This function is mistaken about how large the field matrix is. It believes field has i rows and j columns. That however is not correct. It likely has some larger number of rows and columns.

For example, if you call this function with i==0 and j==0, the array declaration for that call is cell field[0][0], i.e. an empty array which is not valid.

You need to pass in the actual dimensions as additional parameters and use those for the array size.

int checkNeighbor(int i, int j, int rows, int cols, cell field[rows][cols]);
Comments