C ++:我在指向3D数组的指针时遇到问题-我正在编写一个带有2D数组的基本游戏,每个2D数组都是一个单独的关卡,这些关卡分组为一个称为map的3D数组。
如何指向游戏的每个“级别”?我的简化代码:
#include<iostream>
using namespace std;
#define LEVEL 2
#define HEIGHT 3
#define WIDTH 3
bool map[LEVEL][HEIGHT][WIDTH] = { {{1, 0, 1},
{1, 0, 1},
{0, 0, 1}},
{{1, 1, 0},
{0, 0, 0},
{1, 0, 1}} };
int main()
{
// ideally this points to level#1, then increments to level#2
bool *ptrMap;
for(int i=0; i<HEIGHT; i++)
{
for(int j=0; j<WIDTH; j++)
cout << map[1][i][j]; // [*ptrMap][i][j] ?
cout << endl;
}
return 0;
}
分配,
bool *ptrmap= &map[0][0][0];// gives you level 0
cout<<*ptrmap; //outputs the first element, level 0
cout<<*(ptrmap+9);// outputs first element, level 1
如果您不希望指针线性增加,
i.e. map[0][0][0] as *ptrmap & map[1][0][0] as *(ptrmap + 9)
,建议您使用指针的指针创建矩阵(例如bool *** ptrmap),然后创建一个临时指针以对其进行取消引用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句