【问题标题】:pointers to 3D arrays C++指向 3D 数组 C++ 的指针
【发布时间】:2013-08-16 22:32:02
【问题描述】:

C++:我有一个指向 3D 数组的指针的问题 - 我正在编写一个带有 2D 数组的基本游戏,每个 2D 数组都是一个单独的关卡,这些关卡被分组到一个名为 map 的 3D 数组中。

如何指向我的游戏的每个“关卡”?我的精简代码:

#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;    
}

【问题讨论】:

  • 结构体与单色数组的组合更容易理解。
  • 为什么需要指针?
  • 不要使用宏,使用 const

标签: c++ arrays pointers 3d


【解决方案1】:

分配,

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

如果你不想要指针的线性增量,

i.e. map[0][0][0] as *ptrmap & map[1][0][0] as *(ptrmap + 9)

,我建议你使用指针的指针来创建矩阵(例如 bool ***ptrmap),然后创建一个临时指针来取消引用它。

【讨论】:

  • 不应该将多维数组转换为指针:stackoverflow.com/questions/2895433/…
  • 但我相信这不是强制转换,它只是将数组的地址分配给指针
  • 阅读链接的答案。问题在于静态数组和动态数组(Array of arrays)的内存布局不一样。
  • 对不起,我不明白,这与我对这个问题的回答有什么关系,我想我没有理解你的意思。它与这个答案有关还是与 C++ 本身有关?我是 C++ 的相对新手。
【解决方案2】:
bool (*ptrMap)[HEIGHT][WIDTH] = &map[level];
bool (&refMap)[HEIGHT][WIDTH] = map[level];

cout << (*ptrMap)[y][x];
cout << refMap[y][x];

【讨论】:

  • 没有解释?如果 OP 对他的代码感到困惑,他肯定不会理解这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-25
  • 2013-04-19
  • 2023-03-11
  • 2010-10-25
相关资源
最近更新 更多