'Swapping multidimensional arrays in C

I'm doing a code for Elementary Cellular Automata and trying to get it more efficient. One of my goals is to combine it with the Game of Life Cellular Automata in the same array, computing one half values by the Elementary Wolfram rules, and the other by the Conway rules. I've already done it separately with two different logic. Therefore, to accomplish my final goal, I'm doing a 2D array and, first, setting it to generate the new row of Elementary C.A. on the bottom of it, moving everything else one row up and sending the top row to the Game of Life C.A. This is my code so far:

#define Y 7
#define X 15
int main()
{
  int grid[Y][X]={0}, newgrid[Y][X], wr=30, rules[8]; 
  grid [0][X/2]=1;
  int (*g)[X] = grid,(*newg)[X] = newgrid;
  to_binary(&wr,rules); //Transform rule integer into binary number array
  for(int k=0;k<10s;++k)
  {
    for(int i = Y-1;i>=0;--i)
    {
      for(int j = 0;j<X;++j)
      {
        printf("%d",*(g[i]+j));
        if(!i){*(newg[i]+j)=check_cell(j,g[i],rules);} //check cell neighborhood and rules to evolve it
        else{*(newg[i]+j)=*(g[i-1]+j);} //here is my question
      }
      printf("\n");
    }
    //swapping for efficiency (instead of iterating again)
    int (*swap)[X] = g;
    g = newg;
    newg = swap;
    printf("\n");
  }

  return 0;
}

What I was trying to do was, instead of copying every element to the newgrid, copy line by line, and this is what I've tried (only the modified part):

  for(int k=0;k<Y;++k)
  {
    for(int i = Y-1;i>=0;--i)
    {
      for(int j = 0;j<X;++j)
      {
        printf("%d",*(g[i]+j));
        if(!i){*(newg[i]+j)=check_cell(j,g[i],rules);}
      }
      printf("\n");
      if(i>0){*newg[i]=*g[i-1];} //trying to reassign row by row, instead of cell by cell
    }
    int (*swap)[X] = g;
    g = newg;
    newg = swap;
    printf("\n");
  }

But this gets the wrong memory access and does not finish the job properly. Is there a way to do it correctly, reassigning row by row like newg[i]=g[i-1]?

Furthermore, is there any more efficient way to write this code? In the end, I'm going to get it graphic with SDL2. Thanks in advance



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source