指向 3D 数组 C++ 的指针 [英] pointers to 3D arrays C++
本文介绍了指向 3D 数组 C++ 的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
C++:我在使用指向 3D 数组的指针时遇到问题 - 我正在编写一个带有 2D 数组的基本游戏,每个 2D 数组都是一个单独的级别,这些级别被分组到一个名为 map 的 3D 数组中.
C++: I have a problem with pointers to 3D arrays - I'm writing a basic game with 2D arrays, each 2D array is a separate level and these levels are grouped into a 3D array called map.
如何指向游戏的每个级别"?我的精简代码:
How can I point to each 'level' of my game? My streamlined code:
#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;
}
推荐答案
Assign,
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
如果你不想指针线性递增,
If you do not want a linear increment of pointers,
i.e. map[0][0][0] as *ptrmap & map[1][0][0] as *(ptrmap + 9)
,我建议你使用指针的指针来创建矩阵(例如 bool ***ptrmap),然后创建一个临时指针来取消引用它.
, I suggest you use pointer of pointers to create the matrix (ex. bool ***ptrmap) and then create a temporary pointer to dereference it.
这篇关于指向 3D 数组 C++ 的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文