OT: Arrays and ID's

Hi,
I’m currently working on a simple game. The game is played on a grid which is a struct array, Grid[9][9]. I created a function which assigns each grid square an ID for use later, the code is doing it’s job to my knowledge. I’m sure i’m missing some tiny (big?) detail, but i’ve tried numerous ways to fix it to no avail.

void ID (void)
{
ofstream LogFile(“ID.txt”);

int ID = -1;

for (int y = 0;y < 10;y++) {
for (int x = 0;x < 10;x++) {
ID += 1;
Grid[y].ID = ID;
LogFile << "ID " << Grid[y].ID << "
";
}
}
LogFile.close();
LogFile.open(“ID2.txt”);

for (int b = 0;b < 10;b++) {
for (int a = 0;a < 10;a++) {
LogFile << "ID2 " << Grid[a][b].ID << "
";
}
}
LogFile.close();
}

Now when I run the above function, the first pass goes as planned. ID.txt has all the correct ID’s. The second pass SHOULD read back the correct ID’s, however ID’s 1-9 are now 90-98.

Seeing as they were only assigned a few lines above and are simply being read back, i’m clueless as to what’s causing this.

Thank you for your help.

if your grid array is really 9x9, then you should be getting a bus error, cause your iterators loop from 0 to 9. you would be accessing memory outside of the array. either make your grid [10][10] or loop your iterators to 9. i ran this code and had no problems with it, besides what i stated above.

jebus

Thanks for your help Jebus, that fixed it.
I read that zero was counted as the first element in arrays, so I thought [9][9] was 10x10 in actuality.

I read that zero was counted as the first element in arrays, so I thought [9][9] was 10x10 in actuality

the array subscripts tell you how many values are there, so [9][9] is 9x9. but since arrays are 0 based, you must index them from 0 to 8.

jebus

Sounds like maybe you’re coming from a VB background? In VB the array dimension you give is the last element. In C/C++, C#, Java, and most other langauges the dimension you give is the size.