Sign in to follow this  

I am a stupid moron and cannot program

This topic is 4355 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

Bloody hell, I'm having an off day today. I can't believe I can learn and implement a wxWidgets GUI, a setting manager, dators and a templated generalised singleton in a week but can't figure out how to create an array... Hopefully someone can help me out here :) Now, why won't this code work?:

struct tile {
  int type;
};

class whatever {
public:
  whatever();
  tile* environment;
}

whatever::whatever() {
  environment = new tile[100][100];
}

Obviously I've simplified my code somewhat, but these are the relavant bits... So, how about it then? How do I declare a 2D array of tiles, and define it later?

Share this post


Link to post
Share on other sites
You can't use new in that manner. I suggest creating a 1D array of size x*y. Then to access a particular tile use the following:
array[tileY*sizeX+tileX];

Or if you really want 2D arrays:


tile** array;
...
array = new tile*[x];
for(int i=0; i<x; ++i)
array[i] = new tile[y];
...
tile t = array[x][y];





hope that helped.

[Edited by - Sam Gamgee on January 10, 2006 2:22:11 PM]

Share this post


Link to post
Share on other sites
Alternative:

boost::multi_array

~~~begin quote from teh docs~~~

Short Example


What follows is a brief example of the use of multi_array:

#include "boost/multi_array.hpp"
#include <cassert>

int
main () {
// Create a 3D array that is 3 x 4 x 2
typedef boost::multi_array<double, 3> array_type;
typedef array_type::index index;
array_type A(boost::extents[3][4][2]);

// Assign values to the elements
int values = 0;
for(index i = 0; i != 3; ++i)
for(index j = 0; j != 4; ++j)
for(index k = 0; k != 2; ++k)
A[i][j][k] = values++;

// Verify values
int verify = 0;
for(index i = 0; i != 3; ++i)
for(index j = 0; j != 4; ++j)
for(index k = 0; k != 2; ++k)
assert(A[i][j][k] == verify++);

return 0;
}



~~~end quote from teh docs~~~

Share this post


Link to post
Share on other sites

This topic is 4355 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this