Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

pointers to 3D arrays C++

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...