2014-01-07 96 views
0

我搜索了這個網站和谷歌,並沒有真正發現任何解決我的問題。我正在嘗試編寫一個遊戲,並且此遊戲包含玩家可以穿越的地形圖塊地圖。我想將瓷磚存儲在10x10陣列中,但我在初始化陣列時遇到問題。使用二維數組構造C++

我可以初始化數組的第一維,但是錯誤在初始化第一個for循環內的第二維。

這裏是我的代碼如下所示:

//tile on the "map" 
struct tile 
{ 
    char type; 
    bool isWall; 
}; 

void initializeMap(tile * map) 
{ 
    int index1, index2; 

    for(index1 = 0; index1 < 10; index1++) 
    { 
    map[index1] = new tile[10]; 

    for(index2 = 0; index2 < 10; index2++) 
    { 

    } 
    } 
} 

int main() 
{ 
    tile * tileMap = new tile[10]; 
    initializeMap(tileMap); 

    return 0; 
} 

我收到此錯誤:

C:\Users\----\Desktop\TextGame.cpp||In function 'void initializeMap(tile*)':| 
C:\Users\----\Desktop\TextGame.cpp|39|error: no match for 'operator=' in '*(map + ((unsigned int)(((unsigned int)index1) * 2u))) = (tile*)operator new [](20u)'| 
C:\Users\----\Desktop\TextGame.cpp|9|note: candidates are: tile& tile::operator=(const tile&)| 
||=== Build finished: 1 errors, 0 warnings ===| 
+3

自從你將'tile *'打包到map中後,它不需要是'tile **'嗎? – zero298

+0

@ zero298很確定這個問題就在那裏,清理一下並作爲回答發佈 –

+0

@DanF現在發佈 – zero298

回答

4

您正在嘗試一個實際的對象設置爲與命令的指針:

map[index1] = new tile[10];

maptile*。然而,map[index1]是推定的tile*使其實際上是tile,其不能等於tile*其中new tile[10]給你。

因此,代碼將更好地工作爲:

struct tile { 
    char type; 
    bool isWall; 
}; 

/** 
* Initialize the map 
* @param map The array of tile pointers 
*/ 
void initializeMap(tile** map) { 
    int index1, index2; 
    for (index1 = 0; index1 < 10; index1++) { 

     // Set each element of the tile* array 
     // to another array of tile pointers 
     map[index1] = new tile[10]; 

     for (index2 = 0; index2 < 10; index2++) { 
     // Do Something 
     } 
    } 
} 

int main() { 
    // Create a pointer to a set of tile pointers 
    tile** tileMap = new tile*[10]; 
    // Pass it to the initializer 
    initializeMap(tileMap); 
    return 0; 
} 
+0

非常感謝。這更有意義。當我第一次嘗試這樣做時,我試圖使tileMap成爲雙指針,但無法獲得正確的語法。 –

2

注:技術上,那不是2維陣列,是結構的數組的數組。

說,這說明反映你的代碼的問題:您有一個數組的數組,所以第一個分配應分配數組,其內容是指向其他數組

tile** tilemap = new tile*[10]; 

for(std::size_t i = 0 ; i < 10 ; ++i) 
    tilemap[i] = new tile[10]; 

.... 

//Dealocation at program finish: 

for(std::size_t i = 0 ; i < 10 ; ++i) 
    delete tilemap[i]; 

delete tilemap; 

但是你如果你用標準容器,比如std::vector代碼可以改進,而不是手動內存管理,這是容易出錯,:

std::vector<std::vector<tile>> tilemap(10); 

for(std::size_t i = 0 ; i < 10 ; ++i) 
    tilemap.emplace_back(10); 
+2

+1用於推薦使用內存分配。 –

1

我建議使用指向瓦片的共享指針的。這將讓你有不同的瓷磚,並將它們存儲到載體:

struct Tile; // As you declared it. 

struct Water_Tile : public Tile; 
struct Mountain_Tile : public Tile; 
struct Desert_Tile : public Tile; 

// ... 
typedef std::vector< boost::shared_ptr<Tile> > Tile_Container; 

//... 
Tile_Container my_world(10 * 10); 

// ... 
my_world[20] = new Water_Tile; 

共享指針的一個很好的優點是它處理內存管理(刪除)爲您服務。

+0

這很有趣。語法看起來有點嚇人,因爲我還沒有真正困擾過std :: vector的學習。他們可以在飛行中調整大小,但對嗎? –

+0

可以在創建時設置'std :: vector'的大小,或者在使用'push_back'方法時根據需要進行擴展。 –