Cannot allocate memory for a 2 dimentional array of pointers c++ -
so i'm trying create 2 dimensional array of pointers object of type piece. problem when try assign pointer piece array segmentation fault. realized needed initialize array sometime before can start allocating can't right.
here header file of map contains 2-d array of pointers.
#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
the array i'm talking pieces.
i try allocate in constructor of 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 = 0; while(line[i] != 'x') { dimention[i] = line[i]; i++; } stringstream convert(dimention); convert >> width; int temp = i; dimention = ""; = 1; while(line[(i + temp)] != '\0') { dimention[i] = line[(i + temp)]; i++; } stringstream converttwo(dimention); converttwo >> height; (int = 0; < height; i++) { if (!(map.eof())) { getline (map, line); } else { cout << "error file" << endl; break; } (int j = 0; j < width; j++) { pieces[i][j] = piecetype(line[j]); //this i'm getting 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); } } } } }
where name string holds name of file has information loading particular map.
also function piecetype follows:
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 derived class of piece.
the problem indeed have initialize array. this:
pieces=new piece**[height]; for(int i=0;i<height;i++){ pieces[i]=new piece*[width]; }
write after width
, height
, , before start using pieces
. should know: each new
, there should corresponding delete
, or else memory never freed, , memory leak. free memory, add in destructor:
for(int i=0;i<height;i++){ (int j = 0; j < width; j++){ delete pieces[i][j]; } delete[] pieces[i]; } delete[] pieces;
this assumes every pieces[i][j]
contains either object allocated new
or null, , works both. looking @ code, seems case. however, not work if 1 of them not assigned (not case).
Comments
Post a Comment