0
0
C++programming~5 mins

Array size and bounds in C++

Choose your learning style9 modes available
Introduction

Arrays hold many items in order. Knowing their size and limits helps avoid errors when using them.

When you want to store a fixed number of items like scores or names.
When you need to loop through all items safely without going outside the array.
When you want to check if an index is valid before accessing an array element.
Syntax
C++
const int ARRAY_SIZE = 5;
int numbers[ARRAY_SIZE];

// Access elements from 0 to ARRAY_SIZE - 1
for (int index = 0; index < ARRAY_SIZE; ++index) {
    // Use numbers[index]
}

Array indexes start at 0 and go up to size - 1.

Accessing outside these bounds causes undefined behavior (errors).

Examples
This array has no elements, so you cannot access any index.
C++
int emptyArray[0]; // Array with zero size (rarely used)
Array with one element. Only index 0 is valid.
C++
int singleElementArray[1] = {10};
// Valid index: 0
// Invalid index: 1 or more
Accessing index equal to size or more is out of bounds.
C++
int colors[3] = {1, 2, 3};
// Valid indexes: 0, 1, 2
// Accessing colors[3] is out of bounds and unsafe
Sample Program

This program creates an array of 4 scores, prints the size, and prints all scores safely by looping from 0 to size - 1.

C++
#include <iostream>

int main() {
    const int ARRAY_SIZE = 4;
    int scores[ARRAY_SIZE] = {85, 90, 78, 92};

    std::cout << "Array size: " << ARRAY_SIZE << "\n";
    std::cout << "Scores: ";
    for (int index = 0; index < ARRAY_SIZE; ++index) {
        std::cout << scores[index] << " ";
    }
    std::cout << "\n";

    // Trying to access out of bounds (commented out to avoid error)
    // std::cout << scores[ARRAY_SIZE] << "\n"; // Unsafe!

    return 0;
}
OutputSuccess
Important Notes

Time complexity to access an element by index is O(1).

Always check that index is between 0 and size - 1 before accessing.

Common mistake: Accessing index equal to or greater than size causes bugs or crashes.

Use loops with conditions based on array size to avoid out-of-bounds errors.

Summary

Arrays have a fixed size known at creation.

Valid indexes go from 0 up to size minus 1.

Accessing outside these bounds causes errors and must be avoided.