Advertisement

Dynamic arrays???

Started by June 13, 2000 05:08 AM
12 comments, last by jocke 24 years, 6 months ago
I have been trying to do this also... I can dynamically allocate an array like this:

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


But then for some reason I *CAN* access the data one by one like this:

map[2][3] = 4;   


But I can't access it with a loop like this:

for (int i=0 ; i<10 ; i++){map[2] = 3;}   


Perhaps the most strange thing is that my compiler tells me that the program is crashing when I declare
*map = new (int *)[10]   
.

I think that my compiler is trying to optimise things by putting all the loops together or something but the end result is pretty buggered!

Anyone know what is happening?


wise_guy

Edited by - wise_guy on June 13, 2000 9:13:04 PM

Edited by - wise_Guy on June 13, 2000 9:14:31 PM
the reason you can taccess it like
map[2] = 3;
is the same reason as if you didn''t dynamically create the array
like if you created it like
int map[10][10];
you cant say
map[2] = 3;
you need
map[2][something] = 3;
just because it was allocated dynamically.....you still cant try to access an element with only one indes like map[2] = 3;
you need both indexed like map[2][something] = 3;



"Now go away or I shall taunt you a second time"
- Monty Python and the Holy Grail
themGames Productions

Advertisement
The reason why you cant access the variable ala var[1] = 3; is because var is a pointer to an array of pointers. If the compiler lets you get away with var[1] = 3; then you just screwed up one of your arrays and you program will get an access violation.
As for your for loop it should look something like this:
for( int x = 0; x < width; x++ )
for( int y = 0; y < height; y++ )
var[y][x] = 4;[code/]
For the decleration line try:
int **var;<br>for( int y = 0; y < height; y++ )<br> var[y] = new (int)*[width];[code/]<br><font color = "red">OneEyeLessThanNone<br><br><font color = "green">oversleep half hour and be late by one </pre>
Another solution:
    #include &ltvector>using namespace std; // lets us use vector// I'm using "grid" instead of "map" because map is// a kind of data structure.  Just FYItypedef vector< vector< Iso_Tile > > Iso_Grid;// create height # of empty vectorsIso_Grid grid (height);// now create the vector in each height columnfor (int i=0; i<grid.size (); i++)  grid[ i ].resize (width);// now, you can access them like this:Iso_Tile& tile = grid[x][y];// and when you're all done, there's no need to delete// anything because vectors automatically release memory!!    



Edited by - Stoffel on June 15, 2000 1:18:56 PM

This topic is closed to new replies.

Advertisement