An array is a series of elements, each accessed by an index of that array.
If I say
int arr[5] = { 20, 30, 40, 50, 60 };
,
arr has 5 elements in it, accessed through arr[0] to arr[4].
The first element, 20, is access through arr[0].
The second element, 30, is accessed through arr[1].
The third element, 40, is accessed through arr[2].
The fourth element, 50, is accessed through arr[3].
The last (5th) element, 60, is accessed through arr[4].
If an index is "out of bounds", it means that it would be attempting to access an array element that doesn't exist.
For example,
1 2 3
|
int arr[5] = { 20, 30, 40, 50, 60 }; // declare an array of length 5.
arr[5] = 70; // 5 here is out of bounds, because valid array indices only go from 0 to 4
arr[-1] = 42; // -1 here is out of bounds, because arrays start at index 0.
|
If you were to attempt to access an out-of-bounds index, you invoke undefined behavior and your program is wrong.
______________________________________
The best way to check for out-of-bounds array indices is to not let it happen in the first place. Design clear logic in your loops so that it never happens.
But we're only human. Standard library provides
std::vector.
std::vector has the option to throw an exception when an out-of-bounds index is used, through the
at member function. It also has the standard [index] method of accessing elements, which doesn't do bounds checking.
For example,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = { 3, 1, 4, 1, 5 };
vec[0] = 4; // arr is now: { 4, 1, 4, 1, 5 }
//vec[5] = 9; // Undefined behavior: index ouf of bounds
// (No bounds checking was done here)
try
{
vec.at(5) = 9; // use at() function to access elemebnt
}
catch (...)
{
std::cout << "Out-of-bounds exception captured!\n";
}
return 0;
}
|