简体   繁体   English

如何在C中将2d数组元素下移

[英]How to shift 2d array elements down in C

I am trying to shift the contents of a 2d array down when implementing Tetris in C. This is to move the blocks down. 我尝试在C中实现Tetris时向下移动2d数组的内容。这是向下移动块。 The code works but its not moving elements once only, See the image for the problem(The number in the top left corner is the random number that determines the block type). 该代码有效,但不能一次移动元素,请参见图片以查看问题(左上角的数字是确定块类型的随机数)。 Any help appreciated. 任何帮助表示赞赏。 Below is the 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];
        }
    }

http://i61.tinypic.com/xlb58g.jpg http://i61.tinypic.com/xlb58g.jpg

Whenever you shift the contents of an array, you must work in the opposite direction then the shifting. 每当移动数组的内容时,都必须与移动相反的方向进行。 In your case, you need to invert the direction of your 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 the row of unused values to rise up in the array like a bubble. 这使未使用值的行像气泡一样在数组中上升。


Edit: 编辑:
The code above was written to match the apparent intended behavior of the code posted in the question. 上面的代码被编写为与问题中发布的代码的明显预期行为匹配。 If the entire array is to be moved, use this 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];
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM