2014-06-16 118 views
-4

我有一个struct _tile的2d数组。 我想要一个函数返回一个区块。返回指向二维数组中的对象的指针

这里是我用来生成tiles的二维数组的代码,我将要做一些路径查找和地下城工作。

功能GET瓷砖在

enum{normalfloor,door}; 

砖结构。

 struct _tile{ 
int type; 
bool isSet; 
int x,y; 
_tile *camefrom; 
int index; 
bool changeTo(int a){ 
    if(!isSet){ 
     type = a; 
     isSet = 1; 
     return 1; 
    } 
    return 0; 
} 
}; 

地牢地图创建代码:

int Mw,Mh; 
_tile **tile; 
void create(int w = 30,int h = 30){ 
    Mw=w,Mh=h;  
    tile = new _tile *[w]; 
    for(int a=0,_index=0;a<w;a++){ 
     tile[a] = new _tile[h]; 
     for(int b=0;b<h;b++,_index++){ 
      _tile *C = &tile[a][b]; 
      C->type = normalfloor; 
      //1) Start with a rectangular grid, x units wide and y units tall. Mark each cell in the grid unvisited.     
      C->isSet = 0; 
      C->x = a;    
      C->y = b; 
      C->index = _index;    
     }   
    } 
} 

我希望有一个函数在给定的索引返回瓦。 但由于某种原因,这是行不通的。

_tile getTileAt(int index){ 
    int z[2]; 
    int rem = index/Mh; 
    int X = index-(rem*Mh); 
    int Y = index - X; 
    return *tile[X][Y]; 
} 

当我使用这个

  _tile *a; 
     a = getTileAt(10); 
     a->changeTo(door);// here program crashes. 

我一直在寻找在net.but没有得到满意的结果。

+0

这真的是你如何格式化你的代码? –

+0

“这不起作用”调试它。怎么了?你得到的结果是什么?你期望的结果是什么?运用批判性思维。写出纸上的步骤并找出它在哪里分歧。 SO不是一个帮助台。 –

+0

什么不工作? getTileAt的返回值与预期值有什么不同? – Codor

回答

0

你搞砸了余下的计算和计算X。试试这个:

_tile getTileAt(int index){ 
    int X = index/Mh; 
    int Y = index-(X*Mh); 
    return *tile[X][Y]; 
} 

你可以更简单:

_tile getTileAt(int index) { 
    return *tile[index/Mh][index%Mh]; //mod returns the remainder 
} 
+0

是的,这有帮助。 – Fennekin

+0

我刚刚使用了“_tile * a =&tile [index/Mh] [index%Mh]”,而不是使用函数。 – Fennekin