I have two 2D array in C. Let's call them a[row][col] and b[row][col]. I generated random values in array a. Now i want to write a function that will count values, return 2D array and the output would be assigned to array b (it's a convoy game of life).
#include <stdio.h>
#include <stdlib.h>
int row, col = 0;
//creates row boundary
int create_row_line()
{
printf("\n");
for (int i = 0; i < col; i++)
{
printf(" -----");
}
printf("\n");
}
//returns the count of alive neighbours
int count_alive_neighbours(int a[row][col], int r, int c)
{
int i, j, count = 0;
for (i = r - 1; i <= r + 1; i++)
{
for (j = c - 1; j <= c + 1; j++)
{
if ((i < 0 || j < 0) || (i >= row || j >= col) || (i == r && j == c))
{
continue;
}
if (a[i][j] == 1)
{
count++;
}
}
}
return count;
}
int print_state(int x[row][col]){
create_row_line();
for (int i = 0; i < row; i++)
{
printf(":");
for (int j = 0; j < col; j++)
{
printf(" %d :", x[i][j]);
}
create_row_line();
}
}
int count_values(int x[row][col]){
int y[row][col];
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
int neighbours_alive = count_alive_neighbours(x, i, j);
// printf("%d" ,neighbours_alive);
if ((x[i][j] == 0) && (neighbours_alive == 3))
{
y[i][j] = 1;
}
else if ((x[i][j] == 1) && (neighbours_alive == 3 || neighbours_alive == 2))
{
y[i][j] = 1;
}
else
{
y[i][j] = 0;
}
}
}
return y;
}
int main()
{
//change row and column value to set the canvas size
printf("Enter number of rows: ");
scanf("%d", &row);
printf("Enter number of cols: ");
scanf("%d", &col);
int a[row][col], b[row][col];
int i, j, neighbours_alive;
// generate matrix
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
a[i][j] = rand() % 2;
}
}
// print initial state
printf("Initial state:");
print_state(a);
char quit;
do {
printf("Press enter to print next generation. To quit, enter 'q'.");
scanf("%c", &quit);
int** b = count_values(a);
print_state(b);
int** a = b;
} while(quit != 'q');
return 0;
}
But there's an error. I'm a poor C programmer and don't know what should be done to get desirable effect. After assigning the output from function to array b, I want to assign a=b and make a loop from this to make the next generations.
So the question is how to assign values from one 2D array in C to another and how to return 2D array from a function and assign the result to existing 2D array. Thank you for any help