The Array

Matt George

Fractional CTO · Founder of Injuria.ai

•19 min read•

An array is a fundamental data structure in computer science consisting of a collection of elements, typically of the same memory size and data type, stored in contiguous memory locations[1]. Each element in an array is identified by at least one array index or key. Because the elements are stored side by side in the physical memory of a computer, the memory address of any given element can be calculated mathematically in constant time using its index. This mathematical directness makes the array one of the oldest and most widely used data structures in programming.

The primary problem the array solves is the need to store, manage, and iterate over multiple items of related data efficiently without assigning a unique variable name to each item. Before the formalization of arrays in high-level programming languages, programmers had to manually manage memory addresses to group related data. The array abstracts this process, allowing a programmer to declare a single sequence of memory and access any part of it instantly.

Arrays form the building blocks for nearly all other complex data structures, including strings[2], hash tables[3], stacks, queues, and binary heaps[4]. They map directly to the architecture of modern central processing units (CPUs), which fetch data from main memory in contiguous blocks called cache lines. Because of this hardware alignment, arrays provide exceptional performance characteristics for sequential access patterns, making them the default choice for data storage in performance-sensitive applications, scientific computing, and operating system development.

Definition and Core Mechanics

In computer science, an array is defined as a fixed-size sequence of elements stored in a contiguous block of memory. The size of the array is determined at the time of its creation and cannot be changed without allocating a new block of memory.[39] Every element in the array occupies the exact same number of bytes, which allows the computer to treat the entire structure as a uniform grid.

The defining characteristic of an array is its ability to provide constant time access to any element. In Big-O notation[5], accessing or modifying an element by its index has a time complexity of $O(1)$. This is possible because the computer does not need to search through the array to find an element. Instead, it calculates the exact memory address of the element using a simple arithmetic formula.

Searching for a specific value within an unsorted array requires checking each element one by one, resulting in a linear time complexity of $O(n)$, where $n$ is the number of elements. If the array is sorted, algorithms like binary search can find a value in logarithmic time, or $O(\log n)$.

Inserting or deleting an element at the end of an array is an $O(1)$ operation, provided there is allocated space available. Inserting or deleting an element at the beginning or in the middle of an array requires shifting all subsequent elements to maintain contiguous memory. This shifting process takes $O(n)$ time, which is a primary limitation of the array data structure compared to linked lists. The space complexity of an array is $O(n)$, as it requires memory proportional to the number of elements it holds.

The following pseudocode demonstrates the logic and the $O(n)$ cost of inserting a value into the middle of an array:

function insert_at_index(array, length, capacity, index, value):
    if length == capacity:
        return "Error: Array is full"
    if index < 0 or index > length:
        return "Error: Index out of bounds"
    
    // Shift elements to the right to make space
    for i from length down to index + 1:
        array[i] = array[i - 1]
        
    array[index] = value
    length = length + 1
    return "Success"

Because arrays map directly to raw memory, the enforcement of boundaries, ensuring that a program does not attempt to read or write past the end of the allocated space, is a language-level design choice. In memory-safe languages like Java or Rust, the runtime environment or compiler automatically inserts bounds checks, throwing an exception or panicking if an invalid index is accessed. In older systems languages like C and C++, bounds checking is omitted by default to maximize execution speed. This omission allows a program to write data past the end of an array, overwriting adjacent memory structures. This flaw, known as a buffer overflow, is one of the most common and severe security vulnerabilities in software history. The mechanics of exploiting this vulnerability were famously documented in 1996 by Elias Levy (under the pseudonym Aleph One) in the Phrack magazine article "Smashing the Stack for Fun and Profit"[6], which demonstrated how overflowing a local array could overwrite a function's return address and execute arbitrary malicious code.

Memory Layout and Addressing

The mechanism that enables $O(1)$ access is based on memory addressing. When an array is created, the operating system allocates a continuous segment of memory and returns the memory address of the first element. This starting point is known as the base address.

To find the memory address of any subsequent element, the computer multiplies the index of the desired element by the size of a single element in bytes, and adds that offset to the base address.

The formula for a one-dimensional array is:
Address = Base_Address + (Index * Element_Size)

For this formula to work correctly without additional CPU instructions, the index of the first element must be zero. If the index started at one, the formula would require an additional subtraction operation: Address = Base_Address + ((Index - 1) * Element_Size). The zero-based indexing convention was popularized by the BCPL programming language[7] designed by Martin Richards in 1967, and later mathematically justified by computer scientist Edsger W. Dijkstra in a 1982 manuscript titled "Why numbering should start at zero"[8]. Dijkstra argued that zero-based numbering provides the most elegant and error-free way to represent bounds and sequences in computing.

The Element_Size in the formula is dictated by the data type and the architecture of the machine. Compilers also often apply data structure alignment[9]. CPUs read memory in word-sized chunks, typically 4 bytes on 32-bit architectures and 8 bytes on 64-bit architectures. If an array contains complex structures, the compiler might insert invisible padding bytes between elements to ensure each structure aligns with the CPU's word boundaries. The Element_Size must include this padding for the address calculation to remain accurate.

Arrays can also represent multiple dimensions, such as a two-dimensional grid or matrix. Because physical computer memory is strictly one-dimensional, a multidimensional array must be flattened into a linear sequence. There are two primary conventions for this flattening process: row-major order and column-major order[10].

In row-major order, the elements of the first row are stored contiguously in memory, followed immediately by the elements of the second row, and so on. The C and C++ programming languages use row-major order. The address calculation for a two-dimensional array in row-major order is:
Address = Base_Address + ((Row_Index * Total_Columns) + Column_Index) * Element_Size

In column-major order, the elements of the first column are stored contiguously, followed by the second column. The Fortran programming language uses column-major order. The address calculation for column-major order is:
Address = Base_Address + ((Column_Index * Total_Rows) + Row_Index) * Element_Size

Understanding whether a language uses row-major or column-major order is essential for performance. Iterating through a multidimensional array in the wrong order causes the CPU to jump erratically across memory addresses, defeating hardware optimizations and severely degrading execution speed. In modern machine learning, multidimensional arrays are generalized as tensors. The address calculation for an N-dimensional tensor relies on a concept called strides, where a stride defines the number of bytes the computer must skip in memory to move to the next element along a specific dimension.

Discovery and History

The concept of arranging data in a grid or sequence predates electronic computing by centuries, originating in the mathematical study of vectors and matrices. The implementation of arrays in computer hardware and software developed during the 1940s and 1950s.

In 1945, mathematician John von Neumann authored the "First Draft of a Report on the EDVAC"[11], which described a computer architecture featuring a single unified memory space. In the von Neumann architecture, memory is a linear array of addressable words. This hardware design naturally dictated that related data should be stored in contiguous blocks, laying the physical foundation for the array data structure.

The first high-level programming language to formalize the array as a software construct was Plankalkül, designed by German engineer Konrad Zuse between 1943 and 1945. Working in isolation during World War II, Zuse created a language that supported multidimensional arrays and records. Because Zuse lacked the hardware to implement a compiler, Plankalkül remained theoretical and unpublished until 1948, and it did not gain widespread attention until a 1972 publication by F.L. Bauer[12].

The practical popularization of the array occurred with the development of Fortran (Formula Translation) by a team led by John Backus at IBM between 1954 and 1957. Fortran was designed for the IBM 704 mainframe, which was the first mass-produced computer to feature floating-point arithmetic hardware and index registers. Index registers allowed the hardware to rapidly calculate memory offsets, making array iteration highly efficient.

At the time, many programmers were skeptical that a high-level language compiler could generate machine code as fast as hand-written assembly language. To convince the programming community, Backus and his team focused heavily on optimizing array loops. Fortran introduced the DIMENSION statement, which allowed programmers to declare the size of an array, and the DO loop, which provided a simple syntax for iterating over array elements. The resulting compiler produced highly optimized machine code, proving that high-level abstractions could match the performance of hand-coded assembly, as detailed in Backus's retrospective on the History of Fortran[13].

In 1960, the ALGOL 60 specification, edited by Peter Naur, introduced the concept of dynamic array allocation at runtime. As documented in the Revised Report on the Algorithmic Language ALGOL 60[14], ALGOL allowed the bounds of an array to be defined by variables rather than strict compile-time constants, enabling programs to allocate memory based on user input.

Shortly after, in 1962, Harvard professor Kenneth E. Iverson published the book A Programming Language, which laid the groundwork for APL. Iverson designed APL specifically for array programming, introducing a paradigm where mathematical operations are applied to entire arrays at once, rather than requiring explicit loops. This vectorization concept heavily influenced modern numerical computing.

In 1972, Dennis Ritchie developed the C programming language at Bell Labs. C introduced a tight equivalence between arrays and memory pointers. In C, the name of an array acts as a pointer to its base address, and array indexing is defined entirely in terms of pointer arithmetic. This design gave programmers direct, low-level control over memory layout, establishing the array as the primary tool for systems programming, according to Ritchie's account of the Development of the C Language[15].

The Dynamic Array and Amortized Analysis

A strict static array has a fixed size. If a program needs to store more elements than the array can hold, the array will overflow, leading to software crashes or security vulnerabilities. To solve this problem, computer scientists developed the dynamic array[16].

A dynamic array operates by allocating a static array of a certain capacity. When the array reaches its capacity, the system automatically allocates a new, larger static array in a different memory location. The system then copies all elements from the old array to the new array and deallocates the old memory.

Copying elements takes $O(n)$ time, but the performance impact is mitigated by choosing an appropriate growth factor. Most implementations multiply the capacity of the array by a constant factor, typically 2 or 1.5, whenever it resizes.

In 1985, computer scientist Robert Tarjan published a paper titled "Amortized Computational Complexity"[17] in the SIAM Journal on Algebraic and Discrete Methods. Tarjan formalized a mathematical technique called amortized analysis, which evaluates the average time complexity of a sequence of operations rather than the worst-case time of a single operation. Using amortized analysis, Tarjan demonstrated that if a dynamic array grows by a constant geometric factor, the expensive $O(n)$ resizing operations occur infrequently enough that the average cost of an insertion remains $O(1)$.

The choice of growth factor carries specific memory implications. A growth factor of 2, used by the GNU Compiler Collection (GCC) C++ implementation (Java's ArrayList uses a growth factor of 1.5, not 2), means the new array is larger than all previously allocated arrays combined. Because the sum of all previous allocations is always less than the new allocation, this mathematical reality prevents the memory allocator from reusing the contiguous block of memory left behind by previous resizes. A growth factor of 1.5, used by the Microsoft Visual C++ (MSVC) compiler, and some specialized libraries (Python's list uses a growth factor of approximately 1.125, not 1.5), allows the new allocation to eventually fit into the sum of previously freed blocks, improving memory reuse, a design choice extensively documented in libraries like Facebook's Folly FBVector[18].

The dynamic array was standardized for widespread use in 1994 when Alexander Stepanov and Meng Lee presented the Standard Template Library (STL) to the C++ standards committee. The STL included std::vector[19], a highly optimized dynamic array template. The success of std::vector influenced the design of standard libraries in nearly all subsequent programming languages, leading to implementations such as ArrayList in Java[20], list in Python[21], Vec in Rust[22], and slices in Go[23].

Important Variants

While the standard one-dimensional and multidimensional arrays are the most common, several variants have been developed to address specific computational problems.

Variable-Length Arrays

A variable-length array is an array whose length is determined at runtime rather than at compile time, yet it is allocated on the stack rather than the heap.[39] This provides the performance benefits of static arrays without the overhead of dynamic memory allocation. Variable-length arrays were formally standardized in the C programming language in the ISO/IEC 9899:1999[24] specification, commonly known as C99. Because stack memory is highly limited, allocating a large variable-length array can cause a stack overflow, leading later standards like C11 to make this feature optional.

Jagged Arrays

A jagged array, also known as an Iliffe vector, is an array of arrays where each sub-array can have a different length. Instead of storing a perfectly rectangular grid of elements in contiguous memory, the main array stores memory pointers. Each pointer directs the computer to a separate, independently allocated array. Jagged arrays save memory when representing grids with irregular shapes, but they require multiple memory lookups to access a single element, which reduces cache efficiency.

Sparse Arrays

In scientific computing and machine learning, matrices often contain millions of elements, the vast majority of which are zero. Storing these zeros in a standard two-dimensional array wastes massive amounts of memory and processing time. A sparse array[25] compresses this data by storing only the non-zero elements alongside their coordinates. Common formats include Compressed Sparse Row (CSR) and Compressed Sparse Column (CSC). These formats use three separate one-dimensional arrays to encode the values, column indices, and row pointers, allowing algorithms to skip zero values entirely.

Circular Arrays

A circular array, or ring buffer[26], is a fixed-size array used to implement queues and data streams. It maintains two pointers: one for the start of the data and one for the end. When a pointer reaches the end of the allocated memory, it wraps around to the index zero using the modulo operator. This variant allows continuous $O(1)$ insertions and deletions at both ends of the sequence without ever shifting elements or allocating new memory.

Bit Arrays

A bit array[27] stores boolean values compactly by using individual bits within a byte. Since CPUs cannot address individual bits directly, the software uses bitwise operations (AND, OR, shifts) to access them. This reduces memory usage by a factor of eight compared to a standard boolean array, making it highly effective for bloom filters and large-scale flag storage.

Associative Arrays

Although they share the name, associative arrays[28] (often called dictionaries or maps) are abstract data types rather than physical array structures. They allow arbitrary keys, such as strings, instead of sequential integers. Associative arrays are typically implemented using hash tables or search trees, though hash tables rely on a standard physical array under the hood to store their data buckets.

Real-World Applications

Arrays are the underlying mechanism for countless software systems and higher-level data structures.

Strings of text are implemented as one-dimensional arrays of characters or bytes. In the C language, a string is an array of characters terminated by a null byte, as the C standard does not mandate the ASCII encoding[29]. In modern languages, strings are typically arrays of UTF-8 encoded bytes. String manipulation functions, such as searching for a substring or converting text to uppercase, are fundamentally array iteration algorithms.

Hash tables, which provide $O(1)$ key-value lookups, rely on arrays for their internal storage. A hash table computes a numerical hash code from a key, reduces that code using a modulo operation, and uses the result as an index to store the value in a backing array. When two keys produce the same index, a collision occurs, which is often resolved by storing a linked list at that array index or by probing sequentially through the array to find the next empty slot.

Binary heaps, which are used to implement priority queues and the heapsort algorithm, are tree structures that are almost always flattened into arrays. Because a binary heap is a complete binary tree, the relationships between parent and child nodes can be calculated using array indices. For a node at index $i$, its left child is located at $2i + 1$ and its right child at $2i + 2$. This array-based layout eliminates the need to store memory pointers, saving space and improving execution speed.

In scientific computing, arrays are the standard format for numerical simulation and data analysis. The Basic Linear Algebra Subprograms (BLAS)[30] and the Linear Algebra PACKage (LAPACK)[31] are highly optimized software libraries written in Fortran and C that perform matrix operations on contiguous arrays. These libraries form the mathematical foundation for modern tools like NumPy[32] in Python and tensor operations[33] in machine learning frameworks like TensorFlow and PyTorch.

Arrays are strictly required to utilize Single Instruction, Multiple Data (SIMD) processing. Modern processors include special vector registers, such as Intel's Advanced Vector Extensions (AVX), which can perform the same mathematical operation on multiple data points simultaneously. Because SIMD instructions load data in wide, contiguous blocks, the data must be stored in an array format to achieve these hardware-level speedups.

In computer graphics and image processing, images are represented as multidimensional arrays of pixels. A standard high-definition image is a two-dimensional array of rows and columns, where each element is a smaller array of three color channels (red, green, and blue). Graphics processing units (GPUs) are specifically designed to perform parallel mathematical operations on these large pixel arrays.

Arrays also dictate the architecture of modern databases. Traditional relational databases store records in row-major order. Columnar databases, such as Apache Parquet[34] and ClickHouse, store data in column-major arrays. This allows analytical queries that only need one specific field to load only that array into the CPU cache, significantly improving read performance for large-scale data aggregations. To standardize this process across different systems, the Apache Arrow[35] project defines a language-independent columnar memory format. By organizing data in contiguous arrays, Arrow allows different programming languages to share large datasets in memory without the overhead of copying or serializing the data.

Significance and Tradeoffs

The enduring utility of the array in computer science is primarily due to its interaction with modern CPU architecture. Over the past several decades, CPU processing speeds have increased much faster than main memory access speeds. To bridge this gap, CPU manufacturers introduced small, ultra-fast memory banks called caches, located directly on the processor chip.

When a CPU requests a single byte of data from main memory, it does not fetch just that byte. Instead, it fetches a contiguous block of memory. According to the Intel 64 and IA-32 Architectures Optimization Reference Manual[36], modern Intel and AMD processors fetch memory in 64-byte chunks known as cache lines. If a program is iterating through an array, the first element access will cause a slight delay as the cache line is loaded from main memory. The next several elements will already be present in the fast CPU cache, resulting in near-instantaneous access, a process detailed in Ulrich Drepper's paper "What Every Programmer Should Know About Memory"[37].

Hardware prefetchers inside the CPU detect sequential access patterns and preemptively load the next cache lines before the program even requests them. This phenomenon, known as spatial locality, makes arrays orders of magnitude faster to iterate than pointer-based data structures like linked lists, where elements are scattered randomly across memory and cause frequent cache misses.

Arrays also benefit from CPU branch prediction[38]. Because iterating through an array involves a simple, predictable loop counter, the CPU can accurately guess the flow of instructions, avoiding pipeline stalls.

Arrays come with specific tradeoffs regarding memory allocation and modification. The requirement for contiguous memory means that allocating a very large array can fail if the operating system cannot find a single unbroken block of free memory, a condition known as memory fragmentation.

The cost of inserting or deleting elements in the middle of an array remains a strict $O(n)$ operation. For applications that require constant reorganization of data, such as real-time text editors or complex scheduling algorithms, the shifting of array elements becomes a performance bottleneck. In these specific cases, tree-based structures or linked lists are often preferred.

For the vast majority of software engineering tasks, the array provides a highly effective combination of simplicity, memory efficiency, and raw execution speed. From the earliest theoretical designs of the 1940s to the foundation of modern artificial intelligence, the array remains the most essential tool for organizing data in computing.

Sources (39)
  1. Wikipedia: contiguous memory locations
  2. Wikipedia: strings
  3. Wikipedia: hash tables
  4. Wikipedia: binary heaps
  5. Wikipedia: Big-O notation
  6. "Smashing the Stack for Fun and Profit"
  7. Wikipedia: BCPL programming language
  8. cs.utexas.edu: "Why numbering should start at zero"
  9. Wikipedia: data structure alignment
  10. Wikipedia: row-major order and column-major order
  11. Wikipedia: "First Draft of a Report on the EDVAC"
  12. ACM Digital Library
  13. ACM Digital Library
  14. Revised Report on the Algorithmic Language ALGOL 60
  15. Development of the C Language
  16. Wikipedia: dynamic array
  17. "Amortized Computational Complexity"
  18. Facebook's Folly FBVector
  19. `std::vector`
  20. `ArrayList` in Java
  21. `list` in Python
  22. `Vec` in Rust
  23. slices in Go
  24. ISO/IEC 9899:1999
  25. Wikipedia: sparse array
  26. Wikipedia: ring buffer
  27. Wikipedia: bit array
  28. Wikipedia: associative arrays
  29. Wikipedia: null byte
  30. Basic Linear Algebra Subprograms (BLAS)
  31. Linear Algebra PACKage (LAPACK)
  32. NumPy
  33. tensor operations
  34. Apache Parquet
  35. Apache Arrow
  36. Intel
  37. "What Every Programmer Should Know About Memory"
  38. Wikipedia: branch prediction
  39. Kunal Pimparkhede, Computer Programming with C++ (Cambridge University Press, 2017)

Recommended reading