所以我正在尝试创建一个指向Piece类型对象的二维数组指针。问题是当我尝试将一个指针分配给数组时,我得到一个分段错误。我意识到我需要在开始分配之前将阵列初始化到某个时间但我无法做到正确。
这是Map的头文件,其中包含一个2-d指针数组。
#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的派生类。
答案 0 :(得分:2)
问题确实是你必须初始化那个数组。像这样:
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的对象,并且它同时适用于两者。看看你的代码,这似乎是你的情况。但是,如果没有分配其中一个(不是你的情况),它将无法工作。
答案 1 :(得分:0)
使用std::vector<std::vector<Pieces>>
代替(尝试,因为它不起作用)重新发明轮子。它安全,简单,避免了手动内存管理的麻烦。