Jump to content
  • Advertisement
Sign in to follow this  
dhulli

2d Dynamic Array

This topic is 3724 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hey guys, I need a two dimensional dynamic array for a map editor. I have some code which does compile but gives an error during runtime. What i want is a two dimensional dynamic array of type tls (which represent tile info) //This is the tile structure struct tls { int x; int y; int texno; }; //This class handles the second dimension of the array. class da { public: tls* tilearray; void set(int x) { tilearray = new tls[x]; } tls& operator[](int y) { if (!y<0) return tilearray[y]; } }; class tilemap { da *tiles; ... ... public: tilemap(int hTiles,int vTiles) { tiles = new da[hTiles]; tiles->set(vTiles); tiles[0][0].x = 0; //This is where the memory error occurs during runtime. } .... }; if you have an alternate way to apply to 2d dynamic array, please tell me. Thanks

Share this post


Link to post
Share on other sites
Advertisement
If you really want to do it yourself, here's what i would do, roughly.

struct tls;

tls* array = new tls[width*height];//2d represented as 1d

int tex_no = tls[ypos*width + xpos];


You could also encapsulate it in a class

class tls_map{
public:
tls_map(int new_height, int new_width);//set members, init array
~tls_map(){delete[] map;}
tls get_at(int xpos, int ypos){return map[ypos*width + xpos];}
protected:
int width, height;
tls* map;
}


Or use nested std::vectors. Take your pick.

Share this post


Link to post
Share on other sites
You can use a single vector and access it like a two dimensional array:

class Tile { /* ... */ };

class TileMap
{
public:
TileMap(unsigned rows, unsigned columns)
:
rows(rows),
tiles(rows * columns)
{
}

Tile &operator()( unsigned x, unsigned y )
{
return tiles[y * rows + x];
}

const Tile &operator()( unsigned x, unsigned y ) const
{
return tiles[y * rows + x];
}

private:
unsigned rows;
std::vector<Tile> tiles;
};



This is similar to how the compiler actually implements 2D arrays.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!