• Advertisement
Sign in to follow this  

I am a stupid moron and cannot program

This topic is 4421 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
Advertisement
You can't new a 2D array. Use a 1D array and throw in some inline function to translate an (x,y) into an absolute 1D index.

Share this post


Link to post
Share on other sites
Oh. Buggery. Well, thanks for the reply, now I can carry on with my programming rampage... :)

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 = 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[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[j][k] == verify++);

return 0;
}



~~~end quote from teh docs~~~

Share this post


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

  • Advertisement