2012-12-27 39 views
0

好的,大家好!我又有一個問題..我得到一個未處理的異常。SFML 2.0從地圖文件中加載

我跟蹤這個問題回到它的來源是:

openfile >> MapFile[loadCounterX][loadCounterY]; 

唯一的例外是:

Unhandled exception at 0x76ee15de in The Vanity Engine.exe: 0xC0000005: Access violation writing location 0x336e880c. 

它說,這是訪問的衝突呢我訪問的事情是成功地打開這裏:

std::ifstream openfile(filename); 

整個功能是:

//Load map 
void Map::Load(const char *filename) 
{ 
    //Open the file 
    std::ifstream openfile(filename); 
    //Check if file is open 
    if(openfile.is_open()) 
    { 
     //Get mapSizeX and Y from the file 
     openfile >> mapSizeX >> mapSizeY; 
     //While not at the end of the file 
     while(!openfile.eof()) 
     { 
      //Store number at loadCounterX and loadCounterY 
      openfile >> MapFile[loadCounterX][loadCounterY]; //Error here 
      //Increment loadCounterX++ 
      loadCounterX++; 
      //If loadCounterX is less than mapSizeX 
      if(loadCounterX >= mapSizeX) 
      { 
       //Set loadCounterX to 0 
       loadCounterX = 0; 
       //Increment loadCounterY 
       loadCounterY++; 
      } 
     } 
    } 
} 

映射文件是在Map.H

#ifndef MAP_H 
#define MAP_H 

#include "SFML\Graphics.hpp" 
#include "Global.h" 
#include <iostream> 
#include <fstream> 

class Map 
{ 
public: 
    void Load(const char *filename); 
    void Draw(sf::RenderWindow &Window); 
private: 
    int loadCounterX, loadCounterY; 
    int mapSizeX, mapSizeY; 
    int MapFile[100][100]; 
}; 

#endif 
+0

什麼是MapFile,它在哪裏/如何初始化? –

+0

使用Map.H更新的OP – user1816388

+1

mapSizeX和mapSizeY總是<100? – billz

回答

1

loadCounter*應該是本地的功能,或至少初始化爲0,每次你加載。

這是第一次可以正常工作,但是在下次加載之前變量不會重置爲0,導致尋址未分配的空間。

旁註:

請使用某種動態分配(如性病::向量)爲您的地圖數據。每次使用100x100都沒有意義,是嗎?

+0

不,但是我正在學習一個教程,我知道如何使用矢量,但是我寧願隨着教程一起學習,以免它移動太多,最終被卡住和困惑。 ! – user1816388

+0

那麼,在這種情況下,我會尋找更好的教程。無論如何,尋址部分可以與向量矢量相同。 –