Understanding Memory Layout and Characteristics of Arrays

Arrays store elements of the same type in a contiguous block of memory, enabling efficient indexed access based on position.

Key properties:

  • Indexing starts at zero.
  • Elements occupy adjacent memory addresses.

Because of contiguous allocation, inserting or removing an element often requires shifting subsequent items to maintain order.

Element Removal and Overwriting

When deleting an entry at a given position, all later elements must be moved forward. In practice, arrays do not delete items; they overwrite them, since the physical size remains fixed.

One-Dimensional Array Example (C++)

void inspect_mem() {
    char letters[] = {'a', 'b', 'c', 'd'};
    for (size_t idx = 0; idx < sizeof(letters); ++idx) {
        std::cout << static_cast<void*>(&letters[idx]) << " ";
    }
}

Each successive address differs by one byte for char, confirming contiguous placement.

Two-Dimensional Arrays in C++

In C++, multi-row arrays are laid out contiguous in row-major order.

void check_2d_layout() {
    int grid[2][3] = {{10, 20, 30}, {40, 50, 60}};
    std::cout << &grid[0][0] << " " << &grid[0][1] << " " << &grid[0][2] << "\n"
              << &grid[1][0] << " " << &grid[1][1] << " " << &grid[1][2] << "\n";
}

Sample output (addresses in hexadecimal):

0x7ffeefbff520 0x7ffeefbff524 0x7ffeefbff528
0x7ffeefbff52c 0x7ffeefbff530 0x7ffeefbff534

Offsets between consecutive int entries are four bytes, demonstrating uninterrupted linear memory for the entire 2D structure.

Contrast with Java's Array Model

Java abstracts memory addresses from developers. A 2D array is implemented as an array of references to separate inner arrays, which may reside in non-contiguous locations.

public static void show_rows() {
    int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    for (int i = 0; i < matrix.length; i++) {
        System.out.println(matrix[i]);
    }
}

Typical printed values resemble:

[I@4c873330
[I@119d7047
[I@776ec8df

These identifiers are hash-like representations of each inner array object's location, not raw pointers. The lack of sequential pattern confirms that rows can be allocated independently, breaking strict memory continuity across the full 2D construct.

Vector vs Array in C++

A C++ std::vector uses a dynamic array internally but adds features like automatic resizing. Its a container, not a plain array, though its storage remains contiguous.

Tags: Arrays memory layout C++ java Data Structures

Posted on Mon, 20 Jul 2026 17:38:02 +0000 by system_critical