2014-07-07 111 views
0

我是使用SDL編寫圖形遊戲的開始程序員。將tile-sheet分割成片段或「片段」並將其放入數組中的功能,以及將特定「剪輯」繪製到屏幕上的功能無法按預期工作。C++指針參數問題

void split_tilesheet(int width, int height, int space, Entity * ent){ 
    std::cout << "Splitting Tileset..."; 

    int t_width = (width/SPR_W); 
    int t_height = (height/SPR_H); 
    int numTiles = (t_width * t_height); 

    ent = new Entity [numTiles + 1]; 
    if(ent == NULL){ 
     err("!failed to alloc!"); 
    }else{ 
     std::cout << "allocated"<< std::endl; 
    } 
    int count = 0; 
    for(int i = 0; i < t_width; i++){ 
     for(int j = 0; j < t_height; j++){ 

      ent[count].bounds.x = i * SPR_W; 
      ent[count].bounds.y = j * SPR_H; 
      ent[count].bounds.w = SPR_W; 
      ent[count].bounds.h = SPR_H; 
      ent[count].id = ent[i].x + (ent[i].y * t_width); 
      count++; 
     } 
    } 
} 

void draw_room(char tiledata[MAP_MAX_X][MAP_MAX_Y], Entity * ent){ 
SDL_Rect bounds; 
    for(int x = 0; x < MAP_MAX_X; x++){ 
     for(int y = 0; y < MAP_MAX_Y; y++){ 

      if(tiledata[x][y] == '0' || tiledata[x][y] == ' ' || tiledata[x][y] == '\n'){ 
       draw_img(x * SPR_W , y * SPR_H, tiles, bounds, ent[0].bounds); 
      } 
      if(tiledata[x][y] == '1'){ 
       draw_img(x * SPR_W , y * SPR_H, tiles, bounds, ent[1].bounds); 
      } 
     }   
    } 
} 

class Entity 
{ 
public: 
    SDL_Rect bounds; 
    SDL_Surface* sprite; 
    int id; 
    int x; 
    int y; 
    int w, h; 
}; 

我試圖使用指針在運行時動態分配內存。 該程序編譯,但段錯誤。 gdb說段落錯誤是由於draw_room()函數造成的,但我找不到原因。我是路過的draw_room函數指針是:

Entity * floor0_clips = NULL; 

這並沒有工作,要麼

Entity * floor0_clips; 

請幫助...

+0

對該函數的每次調用都在泄漏內存。而'new'在失敗時會拋出一個異常,所以檢查一個空指針是多餘的。 – chris

+0

那麼如何解決內存泄漏?在函數的結尾添加delete [] ent? – glycerinlaminate

+0

使用矢量而不是你必須管理自己的東西。如果你的意思是把'ent'的變化傳播給調用者,那麼使用一個引用。 – chris

回答

2

C++使用傳遞的值(除非你指定通過引用),你沒有。

函數中的變量是給定參數的副本。例如:

int func(int x) 
{ 
    x = 5; 
} 

int main() 
{ 
    int y = 6; 
    func(y); 
    // here, `y` is still `6` 
} 

您的情況與此基本相同。您發送floor0_clips到一個函數,該函數更新它的一個副本,保持原來的不變。

要使用傳遞引用,請將&符號放在函數參數列表中的變量名稱的前面,即Entity * &ent。請勿更改調用該函數的代碼中的任何內容;它是函數的參數列表聲明,用於決定值是通過值還是通過引用傳遞。

注意:無論如何,你似乎分配了太多的實體(爲什麼+ 1?)。

+0

謝謝!現在工作。 – glycerinlaminate