re-declaring variables in c++?

Started by
3 comments, last by tomba 18 years, 3 months ago
ok i have a basic map GLOBAL variables declare like this tile map[30][50]; (tile is a structure i made) so after i read from a file, i found out that i only need to map to be 10x10 (could be any size), so i need re-declare the variable map[30][50] to map[10][10]. it's a waste to have a huge [30[50] variable and not use it fully. i read something about dynamic variables, but it is not clear to me. can someone plez tell me how to redeclare this variable again?
Advertisement
You didn't specify a language, but that looks like it could be C or C++. Assuming C++ there are a couple ways to do this, although none looks incredibly nice without using some 3rd party library like boost. Anyway, what you need is some type of dynamic array, you were correct.

A one dimension dynamic array can be made like this;
int size = 20;tile * map = new map[size];


you can USE this as a two dimensional array pretty easily. If you wanted a 10x11 array

int row = 10;int column = 11;tile * map = new map[row * column];// accessing the [x][y] element:tile temp = map[x + y * column];// stuff// erasedelete[] temp;temp = NULL;


It is far far easier to do a 2d dynamic array that way than the alternative, which is make a pointer to pointer.

int row = 10;int colum = 10;tile ** map = new tile*[row];for(int i = 0; i < row; i++){  map = new tile[column];}


And then you have to delete that stuff when you're done. You can also use vectors in a similar way. Either make a 1d vector, but treat it as a 2d one, or make a vector of vectors. A tutorial on vectors that I think may help is:

http://www.codeguru.com/Cpp/Cpp/cpp_mfc/stl/article.php/c4027

Hope some of that helps.

C++: A Dialog | C++0x Features: Part1 (lambdas, auto, static_assert) , Part 2 (rvalue references) , Part 3 (decltype) | Write Games | Fix Your Timestep!

0) Belongs in For Beginners.
1) Your best bet is probably boost::multi_array. Don't do the work yourself.
2) If you really want to do the work yourself, read this (and the following three sections as well).
3) If I am incorrect in assuming C++, please elaborate.
You could also use a vector of a vector, which might seem a little messy, but it's 'safe' and dynamic:
// Global variable, do not need to set the size if you do not use it yetvector< vector<tile> > map;int Rows = 0;int Cols = 0;// You'd need to get the size before you read in the dataIF >> Rows;IF >> Cols;// Set the array's sizesmap.resize(Rows);for(int x=0;x<map.size();x++)   map[x].resize(Cols);// Read in all the data

Then you can still use map[r][c] as needed. Just another suggestion though.
thx for the help guys, i tried all ways and found nobodynews's method the easieiest. :)

This topic is closed to new replies.

Advertisement