# I am a stupid moron and cannot program

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

## 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 on other sites
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 on other sites
Oh. Buggery. Well, thanks for the reply, now I can carry on with my programming rampage... :)

##### 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 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~~~

1. 1
Rutin
37
2. 2
3. 3
4. 4
5. 5

• 11
• 13
• 12
• 14
• 9
• ### Forum Statistics

• Total Topics
633351
• Total Posts
3011479
• ### Who's Online (See full list)

There are no registered users currently online

×