指向3D数组C ++的指针 [英] pointers to 3D arrays C++

查看:175
本文介绍了指向3D数组C ++的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++:我有一个指向3D数组的指针的问题 - 我使用2D数组编写基本游戏,每个2D数组是一个单独的级别,这些级别被分组为一个称为地图的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆