< Previous | Contents | Next >

Being Aware of Array

Bounds

As you learned, you have to be careful when you index an array. Because an array has a fixed size, you can create an integer constant to store the size of an array. Again, thats just what I did in the beginning of the program:

const int MAX_ITEMS = 10;

Understanding C-Style Strings 101


In the following lines, I use MAX_ITEMS to protect myself before adding another item to the heros inventory:

if (numItems < MAX_ITEMS)

{


}

else

{


}

inventory[numItems++] = "healing potion";


cout << "You have too many items and can’t carry another.";

In the preceding code, I first checked to see whether numItems is less than MAX_ITEMS. If it is, then I can safely use numItems as an index and assign a new string object to the array. In this case numItems is 3, so I assign the string "healing potion" to array position 3. If this hadnt been the case, then I would have displayed the message, You have too many items and cant carry another.

So what happens if you do attempt to access an array element outside the bounds of the array? It depends, because youd be accessing some unknown part of the computers memory. At worst, if you attempt to assign some value to an element outside the bounds of an array you could cause your program to do unpredictable things and it might even crash.

Testing to make sure that an index number is a valid array position before using it is called bounds checking. Its critical for you to perform bounds checking when theres a chance that an index you want to use might not be valid.