Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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;    
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
281 views
Welcome To Ask or Share your Answers For Others

1 Answer

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)

, I suggest you use pointer of pointers to create the matrix (ex. bool ***ptrmap) and then create a temporary pointer to dereference it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...