I want to make the grid and nextgrid arrays into 1d arrays. So, that I can implement per cell threading more easily in CUDA. Currently It causes a segmentation fault when passed particular dimensions from command line. E.g. if gridWidth =6 and gridHeight =8. But will work as intended on some values. E.g. if they are both passed in 6.
So, I would like to know how to correctly initialize a 1d array with pair values and then how to implement this in the nested for loop.
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <cstdlib>
int main (int argc, char *argv[])
{
using namespace std;
//delcare variables
int numIterate = atoi (argv[1]);
int gridWidth = atoi (argv[2]);
int gridHeight = atoi (argv[3]);
cout << "iterate: " << numIterate;
cout << " w: " << gridWidth;
cout << " h: " << gridHeight;
cout << endl;
//make grid
int grid[gridWidth][gridHeight];
int nextgrid[gridWidth][gridHeight];
int genCount=0;
//set all values in grid as 0
for(int i=0;i<gridHeight;i++){
for(int j=0;j<gridWidth;j++){
grid[i][j]=0;
}
}
//insert glider pattern
grid[2][3]=1;
grid[3][2]=1;
grid[4][2]=1;
grid[4][3]=1;
grid[4][4]=1;
for(int k=0; k< numIterate+1; k++){
cout << endl;
cout << endl;
cout << "GENERATION " << genCount <<endl;
for(int i=0;i<gridHeight;i++){
cout << endl;
for(int j=0;j<gridWidth;j++){
int count=0;
count+= grid[i][(j-1+gridWidth)%gridWidth] //left
+grid[i][(j+1+gridWidth)%gridWidth] //right
+grid[(i-1+gridHeight)%gridHeight][j] //up
+grid[(i+1+gridHeight)%gridHeight][j] //down
+grid[(i-1+gridHeight)%gridHeight][ (j-1+gridWidth)%gridWidth] //up-left
+grid[(i+1+gridHeight)%gridHeight][ (j+1+gridWidth)%gridWidth] //down-right
+grid[(i+1+gridHeight)%gridHeight][ (j-1+gridWidth)%gridWidth] //down-left
+grid[(i-1+gridHeight)%gridHeight][ (j+1+gridWidth)%gridWidth] ;//up-right
//return count;
//cout << count;
printf("%d", grid[i][j]);
// Cell is lonely and dies
if ((grid[i][j] == 1) && (count < 2)){
nextgrid[i][j] = 0;
}
// Cell dies due to over population
else if((grid[i][j] == 1) && (count > 3)){
nextgrid[i][j] = 0;
}
// A new cell is born
else if ((grid[i][j] == 0) && (count == 3)){
nextgrid[i][j] = 1;
}
// Remains the same
else{
nextgrid[i][j] = grid[i][j];
}
}
}
//assign current grid to be the next grid
for(int i=0;i<gridHeight;i++){
for(int j=0;j<gridWidth;j++){
grid[i][j] = nextgrid[i][j];
}
}
genCount++;
}
}