2014-06-16 198 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