Reputation: 71
How can I check to see if a dynamic array is out of bounds so I dot not get out of bounds error? I am able to do it with a static array, but having trouble with dynamic. For example:
int *array = new int[10];
int i = 11;
// dynamic array out of bounds
int number = array[i];
delete[] array;
Upvotes: 1
Views: 1496
Reputation: 51845
When you use the new
operator to create an array, there is no in-built way to ask that array how big it is; so, you'll have to keep track of that yourself, by assigning the size to a variable; like this (given you have the requested size in rSize
):
size_t aSize = rSize;
int *array = new int[rSize];
// Later on ...
if (i >= aSize) { /* Error code ... */ }
else { /* do something with/to array[i] */ }
// And, when you're done with "array," you'll need to free its memory...
delete[] array;
However, in Modern C++, you can use the std::vector
container instead, and this does know how big it is:
std::vector<int> array(rSize);
// Later on ...
if (i >= array.size()) { /* Error code ... */ }
else { /* do something with/to array[i] */ }
Furthermore, by using the std::vector
class, you don't need to 'remember' to free that container's used/assigned memory when you've done with it, as it will delete itself (and clean-up all its resources) when it goes out of scope.
EDIT: As pointed out in the comments, if you know your array size at compile time, you can use the std::array
container, rather than std::vector
, which is more efficient for such 'static' arrays. In your case (changing the name of the variable to avoid confusion with the type):
std::array<int, 10> myArray;
// ... etc.
Most of the 'simple' member functions (like myArray.size()
) and operators (like myArray[i]
) can be used in the same way as the std::vector
analogues.
Upvotes: 4
Reputation: 16447
If you know the container size at compile time, use a static container. If you don't know the container size at compile time, there is now way to catch out of bounds errors at compile time but you can catch and handle out of bounds errors at runtime, e.g. with an STL container.
A dynamic array in C++ is std::vector
. Your code would look like
std::vector<int> array(10);
int i = 11;
// dynamic array out of bounds
try {
int number = array.at(i); // with out of bounds check
} catch (std::out_of_range &ex) {
// handle out of bounds exception
}
int number2 = array[i]; // faster, but without out of bounds check
operator[]
accesses the element without check and at
checks if the index is out of bounds.
You should avoid raw new
/new[]
/delete
/delete[]
.
Upvotes: 5