C++ For Loop crash [4.6.1]

I don’t get any errors in my code when compiling but on (Play) it crashes

Here’s my code -

for(int32 CheckNum = 0; CheckNum <= 12; CheckNum++)
{
        if(Inventory[CheckNum]->ItemNum == 4)    //<--- this is the part that crashes???
        {
        }
}

This is the crash message i get but i don’t know how to fix it because it should work?

Hi!

I’m assuming your “Inventory” array does not have 12 items in it. It has less. Say the size of the array is only three, that means you can only access those three members:

  1. Inventory[0] → OK
  2. Inventory[1] → OK
  3. Inventory[2] → OK
  4. Inventory[3] → BAD :frowning:

Once you start accessing items past the end of the array, you’re accessing memory that is not part of that array (memory that doesn’t have an inventory item stored in it). The crash assert you provided is guarding again you doing it. It’s making sure the index (CheckNum) is within the bounds of your array.

To keep from using an invalid index, you probably want your for loop to look like this:

for(int32 CheckNum = 0; CheckNum < Inventory.Num(); CheckNum++)

Using Inventory.Num() instead of 12, ensures that all the values of CheckNum are within the range of your array.

Hopes this makes sense!

I just used “12” as demonstration purposes on my original code i do have
Inventory.Num()
but the crash still occurs, it crashes when i use the “CheckNum” inside of the inventory param’s? why?

Inventory[CheckNum]

Are you really using <= rather than <?

<= will cause it to try and access index 1, rather than stopping when it gets to index 1.