Archived

This topic is now archived and is closed to further replies.

Arrays - Memory Allocation

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

Recommended Posts

I was having a problem before where a variable was in the same memmory location as another. I had an array like this: int Map[18][25]; but it was supposed to be Map[25][18]. I was writing up to Map[25][18], so i see how it could have written past the end of the array, but I was reading some previous posts here about arrays and i thought one said that the computer allocates memmory for 25*18 = 450 integers either way. But if that is the case how could it be writing past the end? How can flipping the array around change anything? I am have been programming in C++ for a couple years, but I still don''t really know how exactly some stuff works yet. t2sherm ô¿ô

Share on other sites
each time you increase y, you jump 25 ints pr y.
int map[y][25]. (y*25 + x, where y -> 0-24, x-> 0-17)

the other way around you jump only 18 ints pr y.
int map[y][18]. (y*18 + x, where y -> 0-24, x-> 0-17)

so you will jump way too far in the map[y][25] array.

Edited by - Claus Hansen Ries on June 21, 2000 11:18:23 AM

Share on other sites
If you've a variable

int Map[18][25]

and you want to access Map[ i ][j], the adress is calculated with

base adress of Map + (25 * i + j)*sizeof(int)

The first adress after the array is &Map[18][0] = &Map[17][25]
= base adress of Map + (25 * 18)*sizeof(int)

so if you want to allocate e.g. element Map[20][0], the adress is

base adress of Map + (25*20)*sizeof(int)

which is past the end of the array.

If you would declare Map[25][18], only 18 would be added so you can have higher first indices although both arrays need the same amount of memory.

GA

Edited by - ga on June 21, 2000 11:33:21 AM

1. 1
Rutin
33
2. 2
3. 3
4. 4
5. 5

• 13
• 9
• 9
• 9
• 14
• Forum Statistics

• Total Topics
633330
• Total Posts
3011384
• Who's Online (See full list)

There are no registered users currently online

×