How to shift 2d array elements down in C -
i trying shift contents of 2d array down when implementing tetris in c. move blocks down. code works not moving elements once only, see image problem(the number in top left corner random number determines block type). appreciated. below array shifting code:
//declare size of board int board [22][10] = {}; //shift down for(i=2;i<20;i++) { for(z=1;z<10;z++) { board[i+1][z] = board[i][z]; } }
whenever shift contents of array, must work in opposite direction shifting. in case, need invert direction of outer loop:
int board [22][10] = {}; for(i = 20; i-- > 2; ) { for(z=1; z<9; z++) { board[i+1][z] = board[i][z]; } }
this allows row of unused values rise in array bubble.
edit:
code above written match apparent intended behavior of code posted in question. if entire array moved, use code:
for(i = sizeof(board)/sizeof(*board) - 1; i--; ) { for(z = 0; z < sizeof(*board)/sizeof(**board); z++) { board[i+1][z] = board[i][z]; } }
Comments
Post a Comment