-2

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;    
}
Harry Lime
  • 2,167
  • 8
  • 31
  • 53

2 Answers2

0
bool (*ptrMap)[HEIGHT][WIDTH] = &map[level];
bool (&refMap)[HEIGHT][WIDTH] = map[level];

cout << (*ptrMap)[y][x];
cout << refMap[y][x];
Jarod42
  • 203,559
  • 14
  • 181
  • 302
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)

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

Stephen Jacob
  • 889
  • 1
  • 15
  • 33
  • Multidimensional arrays should never be casted to pointers: http://stackoverflow.com/questions/2895433/casting-char-to-char-causes-segfault – Manu343726 Aug 17 '13 at 10:24
  • But I believe this is not casting, it is simply assigning the address of the array to the pointer – Stephen Jacob Aug 17 '13 at 10:47
  • Read the answer of the link. The problem is with the memory layout of a static array, and a dynamic array (Array of arrays), is not the same. – Manu343726 Aug 17 '13 at 11:03
  • I am sorry but I don't understand, what's that got to do with my answer to this question, I guess I have not understood your point. Is it something to do with this answer or is it something to do with c++ per se? I am a relative newbie to c++. – Stephen Jacob Aug 17 '13 at 12:28