我们可以给指针无符号字符数组赋值吗?

时间:2020-09-12 21:23:03

标签: c++ arrays pointers dynamic-memory-allocation tetris

大家好,我正在尝试使用C ++制作俄罗斯方块游戏。我正在寻找that tutorial

#include <iostream>
#include <string>
using namespace std;

int nFieldWidth = 12;
int nFieldHeight = 18;
unsigned char *pField = nullptr;   //dynamic memory allocation for store game area elements

int main(){
...

pField = new unsigned char[nFieldHeight * nFieldWidth]; 
for(int x = 0; x < nFieldWidth; x++)
    for(int y = 0; y < nFieldHeight; y++)
        pField[y*nFieldWidth+x] = (x == 0 || x == nFieldWidth - 1 || y == nFieldHeight - 1) ? 9 : 0;
...
system("pause");
return 0;
}

在此条件分支中我们正在做什么?我知道

if(x == 0 || x == nFieldWidth -1 || y == nFieldHeight -1)
   pField[y*nFieldWidth+x] = 9;
else
   pField[y*nFieldWidth+x] = 0;

我们在分配内存吗?如果我们为什么要设置为 9 ,则在全局中我们选择12和18作为边界长度?

1 个答案:

答案 0 :(得分:0)

他在youtube视频中从8:20开始对其进行了解释:如果插槽为空,pField设置为0,否则,如果其被Tetromini形状之一占据,则设置为1至8。 9留给板壁。 因此,在这种三元条件下,他正在初始化电路板,几乎在所有位置都将其设置为空(0),除非循环触及到边缘(0是左边缘,nFieldWidth - 1是右边缘,{{ 1}}是底部边缘),他将在其中放置一个壁槽(9)。