C++

One-Dimensional Arrays in C++

A One-Dimensional (1D) Array is a fundamental data structure in C++ used to store a collection of elements of the same data type in contiguous memory locations. Instead of declaring multiple variables (like score1, score2, score3), you can declare a single array variable to hold all of them.

1. The Theory: Memory and Indexing

Theoretically, an array is a Static Data Structure. This means its size must be known at the time of creation (compile-time) and cannot be changed during the program's execution.

A. Contiguous Memory Allocation

When you declare an array, C++ reserves a solid block of memory. If you have an array of five int elements, and an int takes 4 bytes, C++ reserves 20 bytes of consecutive memory.

  • The Benefit: Because the memory is side-by-side, the CPU can access any element extremely quickly using a simple mathematical formula:

    $$\text{Address of element } i = \text{Base Address} + (i \times \text{Size of Type})$$

B. Zero-Based Indexing

In C++, the first element of an array is always at index 0, not 1.

  • Theory: The index represents the offset from the starting address. The first element is at the start (offset 0), the second is one "jump" away (offset 1), and so on.

  • The N-1 Rule: If an array has $N$ elements, the valid indices are from $0$ to $N-1$.

2. Declaration and Initialization

To use an array, you must specify the data type, the name, and the size (number of elements) inside square brackets [].

A. Declaration

int marks[5]; // Reserves memory for 5 integers. Initially, these contain "garbage values."

B. Initialization

You can provide values at the time of declaration using curly braces {}.

  • int ages[3] = {15, 18, 20};

  • int numbers[] = {1, 2, 3, 4}; // Compiler automatically sets size to 4.

  • int scores[5] = {10, 20}; // First two are 10, 20. The rest are automatically set to 0.

3. Long Theory: The "Bounds" and Safety

One of the most critical theoretical aspects of C++ arrays is that C++ does not perform bounds checking.

  • The Danger: If you have an array of size 5 (arr[5]) and you try to access arr[10], the C++ compiler will not stop you. It will calculate the memory address where the 10th element would be and try to read/write there.

  • The Result: This is known as Buffer Overflow. It can result in:

    1. Garbage Data: Reading random values from memory.

    2. Crashes: Attempting to access memory owned by another process (Segmentation Fault).

    3. Security Risks: Hackers use out-of-bounds access to overwrite critical system memory.

4. Practical Code Example

This program demonstrates how to store values in an array using a loop and how to calculate the average of those values.

#include <iostream>
using namespace std;

int main() {
    // Declaration
    int size = 5;
    double prices[5];
    double sum = 0;

    cout << "Enter 5 product prices:" << endl;

    // Input loop: Filling the array
    for (int i = 0; i < 5; i++) {
        cout << "Price " << i + 1 << ": ";
        cin >> prices[i];
    }

    // Output and Calculation loop
    cout << "\nDisplaying Prices:" << endl;
    for (int i = 0; i < 5; i++) {
        cout << "$" << prices[i] << " ";
        sum += prices[i]; // Accumulating the total
    }

    double average = sum / 5;
    cout << "\n\nTotal Sum: $" << sum << endl;
    cout << "Average Price: $" << average << endl;

    return 0;
}

5. Passing Arrays to Functions

Theoretically, arrays behave differently than single variables when passed to functions.

  • Arrays are passed by address: When you pass an array to a function, you aren't passing a copy of the whole array; you are passing the memory address of the first element.

  • Implication: Changes made to an array inside a function will affect the original array.

  • The Size Problem: Because only the address is passed, the function has no way of knowing how large the array is. This is why we almost always pass the size as a second parameter.

Upcoming Course
Upcoming Course
Learn More
Instructor Tips
Instructor Tips
View Tips
Join Community
Join Community
Join Now