{
  "id": "array-data-structure",
  "title": "Array (Data Structure)",
  "lang": "en",
  "source_lang": "en",
  "summary": "An array is an indexed collection of elements, typically stored at regularly spaced memory locations for efficient direct access.",
  "category": "computer-science",
  "subcategory": "algorithms-theory",
  "type": "concept",
  "aliases": [
    "Indexed array",
    "Array structure"
  ],
  "generated_at": "2026-11-03",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/array-data-structure/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/array-data-structure/",
      "json": "https://aiwiki.page/zh/array-data-structure.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "An array is a data structure that associates elements with positions in an indexed collection. In its conventional implementation, an array stores equal-sized elements in consecutive memory locations, allowing an element’s address to be calculated directly from its index. Arrays provide the foundation for tables, numerical grids, image buffers, and many other representations used throughout computer science.\n\nThe term has two closely related meanings: an indexed collection defined by a programming language, and a particular storage organization. These meanings do not always coincide. Some language-level arrays can grow, contain references to objects of different types, or have missing positions; their implementation need not be a single contiguous block. Conversely, a contiguous array may be hidden inside a higher-level container. Distinguishing the collection’s observable behavior from its physical representation is essential to understanding its performance and semantics."
    },
    {
      "heading": "Indexed collections and address calculation",
      "text": "A one-dimensional array can be modeled as a mapping from a bounded interval of integer indices to values. An array of length \\(n\\) with lower bound \\(L\\) has valid indices \\(L,L+1,\\ldots,L+n-1\\). Its length is the number of elements, not the greatest valid index. Zero-based indexing makes the valid interval \\(0\\) through \\(n-1\\), whereas one-based indexing makes it \\(1\\) through \\(n\\). Some languages also permit explicitly chosen lower bounds, including negative values.\n\nFor a conventional contiguous array, let \\(B\\) be the address of its first element and \\(s\\) the storage size of one element, measured in bytes. The address of element \\(i\\) is\n\n\\[\\operatorname{address}(A[i])=B+(i-L)s.\\]\n\nThis formula explains the array’s defining access property: locating an element requires a fixed amount of arithmetic rather than traversal through earlier elements. If an array begins at byte address 1000, uses four bytes per element, and is zero-indexed, element 6 begins at address 1024. The formula assumes that addresses and offsets are representable and that the array has been validly allocated.\n\nEqual-sized storage slots do not require every value ultimately represented by an array to have the same size. An array of references uses fixed-sized reference slots; each reference may identify a separately allocated object. Thus an array can provide direct access to strings of different lengths without storing the strings themselves inline. Its contiguous storage is the sequence of references, not necessarily the referenced objects.\n\nThe index set and element type form part of the array’s logical description. The storage address, element stride, allocation ownership, and bounds may instead belong to implementation metadata. A runtime descriptor can carry this information when it is not known statically. By contrast, some compiled languages allow much of it to be determined by the compiler, avoiding a separate runtime descriptor for every array.\n\nArrays are ordinarily distinguished from associative collections, whose keys may be arbitrary values rather than positions in a bounded integer interval. An integer-keyed hash table therefore does not become a conventional array merely because its keys are numbers. Likewise, a mathematical sequence specifies values and order but does not prescribe memory layout, mutability, or computational cost. The array concept connects this ordered, indexed abstraction with an implementation that makes positional access inexpensive."
    },
    {
      "heading": "Operations and their computational costs",
      "text": "The standard analysis of arrays uses a random-access machine model in which reading a machine word, performing basic address arithmetic, and accessing an address each take constant time. Under these assumptions, reading or replacing an existing array element takes \\(O(1)\\) time. This is a statement about time complexity, not a promise that every access takes the same number of nanoseconds on physical hardware.\n\nTraversing all \\(n\\) elements takes \\(O(n)\\) time. Searching an unsorted array for a particular value also takes \\(O(n)\\) time in the worst case because every element may need examination. A sorted array permits binary search, which repeatedly halves the remaining candidate interval and uses \\(O(\\log n)\\) comparisons. That improvement depends on maintaining an ordering and having suitable comparison operations; it does not follow from contiguous storage alone.\n\nInsertion has several meanings. Replacing a value in an existing slot is constant-time, but inserting a new value into an ordered sequence while preserving all existing elements generally requires moving later elements. Inserting before position \\(i\\) of a length-\\(n\\) array-based sequence can require moving \\(n-i\\) elements. Deletion similarly shifts subsequent elements toward the beginning. Both operations therefore have \\(O(n)\\) worst-case cost, even when sufficient storage is already available.\n\nIf sequence order is irrelevant, deletion can instead replace the removed element with the last element and shorten the logical sequence. That operation requires only a constant number of element moves. It changes the order and may invalidate assumptions about which index identifies which object. Complexity claims consequently depend on the precise operation contract, not just on the name of the container.\n\nThe cost of an “element move” also requires qualification. Moving a machine integer or a reference is usually treated as constant-time. Moving a large inline record involves more bytes, while copying an object may invoke language-defined behavior. If comparisons themselves are expensive, the number of comparisons and the total running time are different measures. An algorithm operating on arrays may therefore be analyzed in terms of element accesses, comparisons, bytes transferred, or object operations.\n\nAn array holding \\(n\\) fixed-sized elements occupies \\(O(n)\\) space, apart from descriptors and allocation overhead. Additional working storage depends on the algorithm. Some sorting algorithms rearrange elements within the original storage, whereas merge sort implementations commonly use an auxiliary array. The array representation does not by itself determine whether an algorithm is stable, in-place, or efficient for a particular workload."
    },
    {
      "heading": "Multidimensional arrays, shapes, and views",
      "text": "A multidimensional array associates values with tuples of indices. Its rank is the number of indexing dimensions, and its shape gives the extent of each dimension. A two-dimensional array of shape \\(3\\times4\\) has 12 elements. Although such an array can represent a mathematical matrix, storage concepts such as strides, ownership, and mutable views are separate from the mathematical properties of matrices.\n\nConventional memory is addressed linearly, so multidimensional indexing must be translated into a one-dimensional offset. For a zero-indexed array with \\(m\\) rows and \\(n\\) columns, row-major order gives\n\n\\[\\operatorname{address}(A[i,j])=B+s(in+j),\\]\n\nwhile column-major order gives\n\n\\[\\operatorname{address}(A[i,j])=B+s(i+mj).\\]\n\nRow-major storage places successive elements of a row together; column-major storage places successive elements of a column together. Neither arrangement changes the logical value at a given index pair, but it changes which traversal orders access neighboring memory locations.\n\nA general strided representation stores a byte stride \\(t_k\\) for each dimension. With lower bound \\(L_k\\) in dimension \\(k\\), the address formula is\n\n\\[\\operatorname{address}(A[i_0,\\ldots,i_{d-1}]) = B+\\sum_{k=0}^{d-1}(i_k-L_k)t_k.\\]\n\nThis representation supports more than contiguous rectangular blocks. A subarray selecting every second element can have a doubled stride. A reversed view can have a negative stride, with its starting address adjusted accordingly. A transpose of a two-dimensional array can often be represented by exchanging dimensions and strides without moving the underlying elements.\n\nA slice selects part of an array, but languages differ on whether slicing creates an independent copy or a view sharing existing storage. With a view, a write through one array object may become visible through another. Some selection operations, especially those using arbitrary lists of indices, are better represented by gathering elements into a new array rather than by a single stride formula. Reshaping can likewise be metadata-only in some cases and require copying in others.\n\nRectangular arrays also differ from arrays of arrays. A rectangular \\(m\\times n\\) array has uniform row length and may occupy one contiguous block. An array of row references can point to separately allocated rows, potentially with different lengths. Such a jagged representation is useful for irregular data, but accessing an element may require an additional reference lookup. Its rows are not necessarily adjacent in memory. Consequently, identical-looking indexing syntax does not establish identical storage layout or performance."
    },
    {
      "heading": "Dynamic arrays and amortized growth",
      "text": "A dynamic array combines array-style indexing with a resizable logical sequence. It normally maintains a backing allocation, a current length \\(n\\), and a capacity \\(C\\), where \\(n\\leq C\\). The length counts active elements; capacity describes how many elements the allocated storage can accommodate before growth requires a larger allocation. These quantities must not be confused with the fixed extent of the underlying storage block.\n\nAppending when \\(n<C\\) places an element in the next available slot and increments the length. When \\(n=C\\), a typical implementation allocates a larger block, transfers existing elements, and releases or abandons the old block according to the language’s memory-management rules. The growth factor is an implementation policy. Factors near 1.5 or 2 are common, but particular containers and runtime versions need not use the same sequence of capacities.\n\nGeometric growth gives an important aggregate bound. If capacity doubles, the number of existing elements transferred during successive expansions is proportional to\n\n\\[1+2+4+\\cdots+2^k<2^{k+1}.\\]\n\nOver a sequence of \\(n\\) appends, the total transfer work is therefore \\(O(n)\\), making append \\(O(1)\\) in amortized analysis. A single append that triggers reallocation can still take \\(O(n)\\) time. Amortized constant time describes the total cost spread across a sequence; it is not a worst-case latency guarantee and does not require a probabilistic assumption.\n\nGrowing by a fixed number of slots behaves differently. If capacity increases by one every time, appending \\(n\\) elements can cause approximately \\(1+2+\\cdots+(n-1)\\) elements to be transferred, giving \\(O(n^2)\\) total work. Geometric growth avoids that pattern by retaining spare capacity. Reserving space in advance can reduce reallocations when an eventual size is known, although constructing active elements and reserving unused storage are distinct operations in some languages.\n\nShrinking policies also matter. Immediately reducing capacity after every deletion can cause repeated growth and contraction when a workload alternates between insertion and removal. Implementations may retain capacity or shrink only after utilization falls below a lower threshold. This separation between growth and shrink thresholds prevents oscillation near a single boundary.\n\nReallocation has semantic consequences beyond its copying cost. Pointers, references, iterators, or views into the previous allocation may become invalid, depending on the language and container. Element transfers can also invoke constructors or other operations rather than simply copying bytes. Dynamic arrays thus preserve the central benefit of direct indexed access while adding policies concerning capacity, ownership, element lifetime, and reference stability."
    },
    {
      "heading": "Array semantics across programming languages",
      "text": "Programming languages use array-like syntax for several different abstractions. Their differences include whether bounds form part of a type, whether elements are stored inline, whether lengths can change, and whether out-of-range access is checked. The expression a[i] alone reveals little about these properties. A language specification defines the observable behavior; a runtime or compiler may choose among several representations consistent with it.\n\nIn the C programming language, an array contains a fixed number of elements of one type, laid out contiguously. In many expressions, an array expression is converted to a pointer to its first element, but an array and a pointer are not the same type of object. For example, applying sizeof directly to an array object measures the entire array, whereas applying it to a pointer measures the pointer. An array parameter declaration is adjusted to a pointer parameter, so the function does not receive the complete array merely through that declaration.\n\nC also illustrates how bounds information can be absent from an access operation. A pointer to an element does not generally carry the length of the surrounding array. Programs must obtain that information through another part of the interface or through other program knowledge. Multidimensional C arrays are arrays whose elements are themselves arrays; their row-major organization follows from this nested contiguous layout.\n\nOther languages separate fixed arrays from growable containers more explicitly. C++ provides built-in arrays, std::array, and std::vector, with different ownership and resizing behavior. Rust distinguishes fixed arrays, borrowed slices, and growable vectors. Java arrays have a length fixed at creation and bounds-checked indexing; multidimensional Java arrays are arrays of array references, allowing rows to have different lengths. These distinctions affect interoperability as well as ordinary application behavior.\n\nPython’s built-in list is a resizable sequence generally implemented in CPython as an array of object references, rather than as a packed array of the objects’ payloads. Specialized numerical libraries provide homogeneous multidimensional arrays with explicit shapes and strides. JavaScript’s Array has indexed-property and length semantics that permit holes: a missing property at an index is observably different from a present property whose value is undefined. JavaScript typed arrays instead expose fixed-format numeric elements over binary storage.\n\nFortran supports multidimensional arrays, explicit bounds, array expressions, and sections, with column-major element order. These features make array operations central to numerical programs rather than merely a convention built from pointer arithmetic. Across these languages, similarly named features may provide different guarantees, making the language-level contract essential when interpreting complexity claims or exchanging data between independently compiled components."
    },
    {
      "heading": "Memory hierarchy and hardware performance",
      "text": "Arrays are particularly effective when access patterns align with the memory hierarchy. Modern processors do not usually fetch a single requested byte from main memory in isolation. They transfer blocks into a CPU cache, making nearby data available together. Sequentially traversing a packed array can therefore reuse each fetched block efficiently, while following references to scattered objects may require many unrelated transfers.\n\nFor an illustrative 64-byte cache line and eight-byte array elements, one aligned line can hold eight elements. A sequential traversal may use all eight after a single line fill. If each element instead resides in a separate allocation on a different line, a comparable traversal can transfer much more data. Actual performance depends on alignment, cache organization, prefetching, and what other data shares those lines, so the example describes locality rather than a universal speed ratio.\n\nContiguous access also assists hardware prefetchers and single-instruction, multiple-data execution. A vector instruction can process several adjacent numbers together, while predictable streaming access makes future memory requests easier to anticipate. Compilers still need evidence that vectorization preserves semantics: dependencies between iterations, possible aliasing, alignment requirements, and floating-point rules can prevent or alter the transformation. Arrays make these optimizations possible but do not ensure them.\n\nFor multidimensional arrays, loop order can determine whether adjacent accesses are nearby or widely separated. In a row-major matrix, scanning across a row uses consecutive elements, while scanning down a column advances by the row width. Cache blocking reorganizes a calculation into subproblems whose working data can remain in a cache. In matrix multiplication, the objective is not just fewer arithmetic operations but greater reuse of values before they leave fast memory.\n\nThe layout of records introduces another choice. An array of structures stores complete records consecutively, such as x, y, z coordinates for each particle. A structure of arrays stores all x coordinates together, all y coordinates together, and all z coordinates together. The first suits operations consuming whole records; the second can improve bandwidth use and vectorization for operations that process one field across many records.\n\nIn parallel computing, contiguous storage requires attention to sharing. Different threads can update distinct elements that occupy the same cache line, causing coherence traffic known as false sharing. On a graphics processing unit, neighboring threads often achieve better memory throughput when their requests can be combined into fewer transactions. These effects explain why the theoretical \\(O(1)\\) cost of indexing coexists with large practical differences between access patterns."
    },
    {
      "heading": "Bounds, ownership, and correctness",
      "text": "An array access is valid only when its index belongs to the array’s index set and the underlying storage remains valid. For a zero-based array, the usual bounds condition is\n\n\\[0\\leq i<n.\\]\n\nConfusing the length with the final valid index produces a common off-by-one error. A loop using \\(i\\leq n\\) rather than \\(i<n\\) attempts one access beyond the end unless its body contains other logic that prevents that access.\n\nUnchecked out-of-bounds writes can cause a buffer overflow, corrupting adjacent storage or program control data. Out-of-bounds reads can expose unrelated data or cause a failure. Languages with checked indexing typically reject the access through an exception, panic, or another defined mechanism. In C and C++, many invalid accesses instead have undefined behavior, allowing compilers to optimize on the assumption that valid programs do not perform them.\n\nBounds checking need not mean a separate machine-level comparison for every source-level access. A compiler can sometimes prove that all iterations of a loop remain within bounds and eliminate redundant checks. A loop invariant relating the index, array length, and progress of the computation supplies the reasoning behind such transformations. When the proof is unavailable, runtime checks preserve the language’s required behavior.\n\nCorrect bounds alone are insufficient if the address calculation overflows. Allocation size computations such as \\(n\\times s\\) can produce an incorrectly small result when evaluated in an integer type that cannot represent the mathematical product. A program may then allocate less storage than its later indexing assumes. Similar problems arise when combining multidimensional extents or converting between signed and unsigned index types. Correctness requires both a valid logical index and a representable, valid storage calculation.\n\nOwnership introduces a separate class of hazards. A slice or pointer can describe positions that were originally within bounds but refer to storage that has since been released or replaced. Dynamic-array reallocation is a common source of this problem. Garbage collection can keep reachable objects alive, but it does not automatically prevent unintended shared mutation or every form of view invalidation defined by a container’s interface.\n\nFinally, sharing an array between concurrent computations requires rules for conflicting accesses. A bounds-valid write can still participate in a data race if another execution thread accesses the same location without the required synchronization. Formal verification of array-manipulating programs consequently addresses several properties at once: valid indices, preserved ownership or lifetime, appropriate synchronization, and the relationship between the final contents and the intended computation."
    },
    {
      "heading": "Arrays as building blocks and scientific representations",
      "text": "Arrays support many data structures whose public interfaces are not primarily positional. A stack can use the end of a dynamic array for push and pop operations. A circular buffer uses a fixed allocation with indices that wrap around its end, supporting queue-like behavior without shifting all remaining elements after removal. Hash tables commonly use arrays for buckets, entries, or control information, although their lookup semantics are based on keys rather than sequence positions.\n\nA binary heap provides another example. In a zero-indexed array representation, the children of a node at position \\(i\\) occupy positions \\(2i+1\\) and \\(2i+2\\), when those positions exist; the parent of a non-root node is at \\(\\lfloor(i-1)/2\\rfloor\\). The indexing formulas encode the structure of a complete binary tree without storing an explicit pointer for every edge. The heap’s ordering invariant is a separate property maintained by its update algorithms.\n\nIn numerical computing, arrays represent vectors, matrices, sampled functions, and higher-dimensional data. An image may be stored with dimensions for height, width, and color channel. A sound signal may use dimensions for sample position and channel. A machine-learning system can represent a batch of images by adding a batch dimension. The meanings of the dimensions belong to the application; the storage descriptor records extents and strides rather than necessarily identifying their scientific interpretation.\n\nDense arrays allocate space for every position, including positions whose value is zero. For large, mostly zero data, a sparse matrix representation can instead store nonzero values with auxiliary indices. Compressed sparse row storage, for example, uses arrays of values, column indices, and row-boundary offsets. This saves space when sparsity is substantial but replaces simple dense addressing with searches or indexed traversal through the compressed representation.\n\nArrays also underpin column-oriented database processing. Keeping values from one field together allows a query to scan or aggregate that field without necessarily reading complete records. Null indicators, compressed encodings, and variable-length fields add auxiliary arrays and offsets, so a database column is not always one plain array of fixed-sized application values.\n\nThese applications expose the limits as well as the strengths of the representation. Arrays work especially well when positions have stable meaning, traversal is common, or compactness matters. Workloads dominated by insertion into the middle, stable object addresses, or extremely sparse index spaces may favor linked, tree-based, segmented, or hashed structures. Hybrid designs often retain arrays inside their components while changing the organization that connects those components."
    },
    {
      "heading": "Historical development and array programming",
      "text": "Arrays became important early in electronic computing because scientific calculations naturally involved tables, vectors, and matrices. Stored-program computers provided addressable memory, while instructions and addressing conventions made it possible to compute which location contained a desired value. Indexed addressing reduced the need to write separate instructions for each table position, connecting mathematical subscripts with operations that machines could execute repeatedly.\n\nThe first Fortran compiler, delivered by IBM in 1957, made array manipulation accessible through a high-level notation intended for scientific and engineering work. Multidimensional arrays and subscripted references allowed programmers to express numerical calculations without manually translating every access into assembly-level address arithmetic. Fortran’s column-major ordering became an enduring interface convention for numerical libraries, influencing how software written in other languages exchanges matrix data with them.\n\nALGOL 60 further developed arrays as language-level objects with declared bounds and multidimensional indexing. Its treatment of bounds emphasized that zero-based indexing is a design choice rather than a defining mathematical property of arrays. Later languages adopted different compromises among flexible bounds, compile-time size information, runtime descriptors, and simple machine-level representations.\n\nC emerged at Bell Labs in the early 1970s with arrays closely connected to pointer arithmetic. Its approach exposed storage layout and address manipulation directly, supporting systems programming and compact interfaces. The resulting conventions became influential through operating systems, binary interfaces, and libraries. Their influence also made the distinction between an array object and a pointer to an element a persistent topic in programming-language education.\n\nA different tradition developed around array programming, in which whole arrays are operands rather than merely containers accessed one element at a time. Kenneth E. Iverson’s 1962 book A Programming Language presented the notation from which APL developed. APL and later array-oriented systems emphasized operations such as reduction, transposition, and combinations of whole collections. These systems made array shape and rank central to the expression of algorithms.\n\nSubsequent numerical environments and libraries carried array-oriented ideas into scientific computing, data analysis, and machine learning. Whole-array syntax can describe a computation independently of the particular loop nest used to execute it. Implementations may then select vector instructions, parallel kernels, or optimized library routines. At the same time, interoperability between these systems continues to depend on concrete details inherited from earlier traditions: element representation, row-major or column-major order, index conventions, strides, and ownership of the underlying storage."
    }
  ],
  "links": [
    "data-structure",
    "computer-science",
    "programming-language",
    "byte",
    "metadata",
    "compiler",
    "hash-table",
    "time-complexity",
    "binary-search",
    "algorithm",
    "sorting-algorithm",
    "merge-sort",
    "matrix",
    "dynamic-array",
    "amortized-analysis",
    "c-programming-language",
    "fortran",
    "memory-hierarchy",
    "cpu-cache",
    "aliasing",
    "parallel-computing",
    "graphics-processing-unit",
    "loop-invariant",
    "garbage-collection",
    "formal-verification",
    "stack-data-type",
    "binary-tree",
    "machine-learning",
    "sparse-matrix",
    "database"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}