简体   繁体   中英

Error with c++ Arrays and Memory

I have been working on converting a batch game I created to c++ for its further advancement, and have run into numerous problems, one of which is the array I need for the nodeMatrix (world map). I need a 100 x 100 map with 20 data values per meter.

 int nodeMatrix[99][99][19];

But the problem with it is when I try to set the null(or ungenerated) state of the map, it crashes with (0xC0000005), so I added a visual to the script that prints the current node being reset (it's much slower though),

void emptydata(){

  int temp_x = 0;

  int temp_y = 0;

  int temp_t = 0;

  do{

     temp_y = 0;

     do{

         temp_t = 0;

         do{

             nodeMatrix[temp_x][temp_y][temp_t] = 0;

             //visual

             cout << temp_x << " " << temp_y << " " << temp_t << endl;

             temp_t ++;

         }while(temp_t <= 50);

         temp_y ++;

     }while(temp_y <= 99);

     temp_x ++;

 }while(temp_x <= 99);

}

It crashes at 99 14 10 each time, (it starts at zero so 100 15 11), would that be 16500 bites data?

Anyway, is it something with memory allocation? I cant figure it out.

It sounds like your problem is that you have allocated a 99 by 99 by 19 array, rather than a 100 by 100 by 20 array. Array declaration takes the number of elements, not the max index.

I'm not sure how you got to temp_y = 14 and temp_t = 10, but this seems to be confirmed by the fact that it crashes at temp_x = 99.

If you post that actual error message it would be more helpful.


It appears that you also limited temp_t by 50, rather than 20, but I think that was a typo. Also, as a stylistic note, for loops are more common in c++, as they will handle indexing for you.

Your definition says [99][99][19] but you are checking for [100][100][51] (while(temp_t <= 50), while(temp_y <= 99), temp_x <= 99).

temp_t will go from 0 to 50 -> 51 elements.

temp_y will go from 0 to 99 -> 100 elements.

temp_x will go from 0 to 99 -> 100 elements.

When you get out of the reserved memory for the array you get a protected memory exception...

Also, for clarity, use for loops:

int nodeMatrix[100][100][20];

for(int x = 0; x < 100; x++)
{
    for(int y = 0; y < 100; y++)
    {
        for(int z = 0; z < 20; z++)
        {
            nodeMatrix[x][y][z] = 0;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM