Mediocre Human
Mediocre Human

Reputation: 23

Conway's Game of Life (C) - Coordinates not Corresponding to 2D Array Indexing?

I am trying to program Conway's Game of Life in C. I have created a 2 dimensional array representing the cells. I attempted to solve the game using a system of coordinates.

I wrote a function to create an array that brute forced all possible combinations of the neighbor's coordinates.

Then I looped through the 2d array of cells using a double nested for loop, and counted the number of dead and living neighboring cells.

I have a conditional that checks if the neighboring cells are alive, dead, or non existing (this occurs if the cell in the game is on the edge or the corner of the array).

The only problem is, no matter what I try, I am always counting the wrong number of living and dead cells, which results in subsequent incorrect generations.

I'm pretty sure this is because the system of coordinates that I am using to keep track of the cells does not correspond to the arrays. (I have tried to fix this, and failed)

My question is, what is the correct way to access specific cells inside the 2D arrays, such that the rows and columns of the arrays correspond to the x and y axis?

void bruteforceNeighbors(int ** coord, int i, int j){ 
array[0][0] = i-1;
array[0][1] = j-1;

array[1][0] = i-1;
array[1][1] = j;

array[2][0] = i-1;
array[2][1] = j+1;

array[3][0] = i;
array[3][1] = j-1;

array[4][0] = i;
array[4][1] = j+1;

array[5][0] = i+1;
array[5][1] = j-1;

array[6][0] = i+1;
array[6][1] = j;

array[7][0] = i+1;
array[7][1] = j+1;
} 

//world is the 2d array

char ** world = (char **)malloc(sizeof(char *)*rows);
for (int i =0;i < rows; i++){
    world[i] = (char *) malloc(sizeof(char)*columns);
}

Upvotes: 1

Views: 374

Answers (1)

David Ranieri
David Ranieri

Reputation: 41036

You are reserving space for an array of char * but using int ** inside the function, change to

int **world = malloc(sizeof(int *) * rows);
for (int i =0; i < rows; i++) {
    world[i] = malloc(sizeof(int) * columns);
}

Upvotes: 2

Related Questions