[英]Cannot allocate memory for a 2 dimentional array of pointers c++
因此,我試圖創建一個指向Piece類型對象的二維數組。 問題是當我嘗試將指向數組的指針分配給數組時,出現分段錯誤。 我意識到我需要初始化到數組才能開始分配,但是我做不到。
這是Map的頭文件,其中包含一個二維指針數組。
#ifndef MAP_H
#define MAP_H
#include <iostream>
#include <vector>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <sstream>
#include <string>
#include <cstring>
#include "Player.h"
#include "Sprite.h"
#include "Piece.h"
#include "Messages.h"
#include "PieceType.h"
using namespace std;
class Map
{
private:
Piece*** pieces;
int startingX;
int startingY;
int width;
int height;
string mapName;
public:
Map(string);
~Map();
void printMap() const;
Piece* pieceType(char);
void setSprite(Piece*);
void firstMove();
void resetMap(string);
bool moveUp(int, int);
bool moveDown(int, int);
bool moveLeft(int, int);
bool moveRight(int, int);
int getHeight();
int getWidth();
};
#endif
我正在談論的數組是碎片。
我嘗試在Map的構造函數中分配它。
Map::Map(string name)
{
ifstream map;
string line;
string dimention;
mapName = name;
map.open(name.c_str());
if (map.good())
{
getline (map, line);
int i = 0;
while(line[i] != 'X')
{
dimention[i] = line[i];
i++;
}
stringstream convert(dimention);
convert >> width;
int temp = i;
dimention = "";
i = 1;
while(line[(i + temp)] != '\0')
{
dimention[i] = line[(i + temp)];
i++;
}
stringstream convertTwo(dimention);
convertTwo >> height;
for (int i = 0; i < height; i++)
{
if (!(map.eof()))
{
getline (map, line);
}
else
{
cout << "Error with file" << endl;
break;
}
for (int j = 0; j < width; j++)
{
pieces[i][j] = pieceType(line[j]); //This is where I'm getting the segmentation fault
cout << "assigned" << endl;
if ((pieces[i][j])->getType() == WAYPOINT)
{
if (pieces[i][j]->getWaypointType() == 0)
{
startingX = j;
startingY = i;
}
}
else
{
(pieces[i][j])->setXCordinate(j);
(pieces[i][j])->setYCordinate(i);
}
}
}
}
}
其中name是一個字符串,其中包含文件的名稱,該文件具有用於加載特定地圖的信息。
函數pieceType也如下所示:
Piece* Map::pieceType(char type)
{
Piece* temp;
if (type == '.')
{
return NULL;
}
if (type == 'S')
{
temp = new Waypoint(0);
return temp;
}
if (type == 'E')
{
temp = new Waypoint(1);
return temp;
}
}
Waypoint是Piece的派生類。
問題確實是您必須初始化該數組。 像這樣:
pieces=new Piece**[height];
for(int i=0;i<height;i++){
pieces[i]=new Piece*[width];
}
在獲得width
和height
,在開始使用pieces
之前寫下它。 但是您應該知道一點:對於每個new
,都應該有一個對應的delete
,否則該內存將永遠不會被釋放,並且您將發生內存泄漏。 要釋放該內存,請將其添加到析構函數中:
for(int i=0;i<height;i++){
for (int j = 0; j < width; j++){
delete pieces[i][j];
}
delete[] pieces[i];
}
delete[] pieces;
假定每個pieces[i][j]
包含一個分配了new
或NULL的對象,並且兩者均可使用。 查看您的代碼,這似乎是您的情況。 但是,如果未分配其中之一(不是您的情況),將不起作用。
使用std::vector<std::vector<Pieces>>
代替(嘗試這樣做,因為它不起作用)重新構造輪子。 它安全,容易,並且避免了手動內存管理的麻煩。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.