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

标签 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作为边界长度?

最佳答案

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

关于c++ - 我们可以给指针无符号字符数组赋值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63865049/

相关文章:

c - 如果我通过指针给了数组值,为什么我无法使用数组引用更改数组中的值?

我可以在知道维度之前声明一个指向二维数组的指针吗?

c++ - MPI 可执行文件和共享标准输入

arrays - Swift 使用 for-in 循环替换数组中的字符串

java - 我如何从 Android SDK 解析 PHP 数组?

c++ - 通过指针访问数组元素

将堆栈转换为字符串

python - 当我使用 operator[] 时列出导致错误的项目

c++ - 链接LLVM导致gcov失败

c++ - 如何使用 QDirIterator 遍历特定类型的文件