Skip to main content

2.3 2D & Multi-Dimensional Arrays: Row-Major vs Column-Major Addressing

📚Module 02 • Arrays & Memory AddressingTopic 2.3⏱️21 min read
🎯High-Yield For:Semester Exams • Technical Interviews • Engineering Foundations

💡 Core Intuition: Multi-Dimensional Coordinate Flattening​

To human programmers and mathematicians, a two-dimensional array is an intuitive rectangular grid indexed by rows and columns, and a three-dimensional array is a solid geometric rectangular prism. However, physical computer memory is strictly one-dimensional. Computer hardware address buses index bytes along a flat, contiguous memory rail: 0x00000000,0x00000001,0x00000002,…0\text{x}00000000, 0\text{x}00000001, 0\text{x}00000002, \dots

Therefore, every compiler, runtime interpreter, and hardware address generation unit (AGU) must map high-dimensional coordinate tuples (i,j)(i, j) or (i,j,k)(i, j, k) into a single flat 1D memory offset.

🍳 The Everyday Analogy: Reading a Book vs Scanning a Spreadsheet​

Reading English Prose vs Reading an Accounting Ledger Column.

  • Row-Major Order (RMO): You read English text horizontally from left to right along the entire first line (Row 0), then wrap down to the start of the next line (Row 1), and so on. Elements on the same row reside right next to each other.
  • Column-Major Order (CMO): You read the first entry of line 1, then line 2, then line 3 straight down the left margin (Column 0). Only after exhausting the bottom of the column do you jump to the top of the next column.

💻 Bridging to Computer Science: Cache Lines & Stride Penalties​

Why does the choice between RMO and CMO matter so profoundly to software engineers?

In modern microarchitectures, the CPU does not read individual bytes from RAM; it fetches an entire 64-byte cache line into the L1 data cache. In C, C++, Java, and Python (NumPy), arrays are stored in Row-Major Order. Iterating along a row accesses adjacent bytes sequentially (Stride-1 access), achieving a ∼99%\sim 99\% L1 cache hit rate.

Conversely, iterating down columns in a Row-Major array causes Stride-NN access, jumping N×WN \times W bytes on every iteration. For large matrices (N=4096N = 4096), this evicts active cache lines on every read, incurring full memory bus stalls that make the program run 10 to 50 times slower despite executing the exact same number of arithmetic operations!


🧱 The Multi-Dimensional Linearization Problem​

In C and standard systems programming, a 2D array is declared with row and column dimensions:

int disp[2][4] = {
{10, 11, 12, 14},
{14, 15, 16, 17}
};
// Equivalently stored sequentially in memory as:
int disp[2][4] = {10, 11, 12, 14, 14, 15, 16, 17};

Because RAM cannot represent a grid natively, the compiler must serialize the 2D matrix into a contiguous 1D sequence. There are two canonical conventions for this transformation:

  1. Row-Major Order (RMO): Rows are stored consecutively.
  2. Column-Major Order (CMO): Columns are stored consecutively.

➡️ Row-Major Order (RMO) Addressing Derivation​

In Row-Major Order, elements are stored sequentially row by row. All elements of Row 0 are stored first, followed by all elements of Row 1, and so on.

Mathematical Derivation for Arbitrary Index Bounds​

Let array AA be defined with arbitrary lower and upper index bounds:

A[L1…U1][L2…U2]A[L_1 \dots U_1][L_2 \dots U_2]

Where:

  • L1L_1: Lower Bound of row indices; U1U_1: Upper Bound of row indices
  • L2L_2: Lower Bound of column indices; U2U_2: Upper Bound of column indices
  • Total Rows: M=U1−L1+1M = U_1 - L_1 + 1
  • Total Columns per Row: N=U2−L2+1N = U_2 - L_2 + 1
  • Base Address: B=Address(A[L1][L2])B = \text{Address}(A[L_1][L_2])
  • Element Size: WW bytes

To calculate the memory address of an arbitrary element A[i][j]A[i][j]:

  1. Count Preceding Full Rows:
    To arrive at row ii, the program must traverse all preceding rows from L1L_1 up to i−1i - 1.
    Preceding Rows=i−L1\text{Preceding Rows} = i - L_1

  2. Count Elements in Preceding Rows:
    Each complete row holds exactly N=(U2−L2+1)N = (U_2 - L_2 + 1) elements.
    Elements in Preceding Rows=(i−L1)×(U2−L2+1)\text{Elements in Preceding Rows} = (i - L_1) \times (U_2 - L_2 + 1)

  3. Count Preceding Elements in Target Row:
    Inside the target row ii, elements start at column L2L_2 and proceed up to j−1j - 1.
    Elements Before Target in Row i=j−L2\text{Elements Before Target in Row } i = j - L_2

  4. Sum Total Preceding Elements:
    Total Elements=(i−L1)×(U2−L2+1)+(j−L2)\text{Total Elements} = (i - L_1) \times (U_2 - L_2 + 1) + (j - L_2)

📐Universal Row-Major Order (RMO) Addressing Formulatheorem

For an array A[L1…U1][L2…U2]A[L_1 \dots U_1][L_2 \dots U_2] stored in Row-Major Order:

Address(A[i][j])=B+W×[(i−L1)×(U2−L2+1)+(j−L2)]\text{Address}(A[i][j]) = B + W \times \Big[ (i - L_1) \times (U_2 - L_2 + 1) + (j - L_2) \Big]

Standard 0-Based Indexing (L1=0,L2=0L_1 = 0, L_2 = 0 with NN columns):

Address(A[i][j])=B+W×[i×N+j]\text{Address}(A[i][j]) = B + W \times \Big[ i \times N + j \Big]

Standard 1-Based Indexing (L1=1,L2=1L_1 = 1, L_2 = 1 with NN columns):

Address(A[i][j])=B+W×[(i−1)×N+(j−1)]\text{Address}(A[i][j]) = B + W \times \Big[ (i - 1) \times N + (j - 1) \Big]

⬇️ Column-Major Order (CMO) Addressing Derivation​

In Column-Major Order, elements are stored sequentially column by column. All elements of Column 0 are stored first, followed by all elements of Column 1, and so on.

Mathematical Derivation for Column-Major Order​

To locate element A[i][j]A[i][j] when the array is organized by column:

  1. Count Preceding Full Columns:
    All columns from index L2L_2 up to j−1j - 1 have been stored completely.
    Preceding Columns=j−L2\text{Preceding Columns} = j - L_2

  2. Count Elements in Preceding Columns:
    Each complete column contains exactly M=(U1−L1+1)M = (U_1 - L_1 + 1) rows (elements).
    Elements in Preceding Columns=(j−L2)×(U1−L1+1)\text{Elements in Preceding Columns} = (j - L_2) \times (U_1 - L_1 + 1)

  3. Count Preceding Elements in Target Column:
    Inside column jj, elements begin at row L1L_1 and proceed down to i−1i - 1.
    Elements Before Target in Column j=i−L1\text{Elements Before Target in Column } j = i - L_1

  4. Sum Total Preceding Elements:
    Total Elements=(j−L2)×(U1−L1+1)+(i−L1)\text{Total Elements} = (j - L_2) \times (U_1 - L_1 + 1) + (i - L_1)

📐Universal Column-Major Order (CMO) Addressing Formulatheorem

For an array A[L1…U1][L2…U2]A[L_1 \dots U_1][L_2 \dots U_2] stored in Column-Major Order:

Address(A[i][j])=B+W×[(j−L2)×(U1−L1+1)+(i−L1)]\text{Address}(A[i][j]) = B + W \times \Big[ (j - L_2) \times (U_1 - L_1 + 1) + (i - L_1) \Big]

Standard 0-Based Indexing (L1=0,L2=0L_1 = 0, L_2 = 0 with MM rows):

Address(A[i][j])=B+W×[j×M+i]\text{Address}(A[i][j]) = B + W \times \Big[ j \times M + i \Big]

Standard 1-Based Indexing (L1=1,L2=1L_1 = 1, L_2 = 1 with MM rows):

Address(A[i][j])=B+W×[(j−1)×M+(i−1)]\text{Address}(A[i][j]) = B + W \times \Big[ (j - 1) \times M + (i - 1) \Big]

⚖️ RMO vs CMO Architectural Comparison​

Contrasting memory linearizations, language runtime conventions, and stride multipliers

Row-Major

Row-Major Order (RMO)

➡️
Dominant Architecture / DomainC, C++, Java, Python (NumPy default), C#, Rust
  • •Consecutive elements in memory share the same row: A[i][j] is immediately followed by A[i][j+1].
  • •Row index i advances large memory blocks; column index j advances unit word strides.
  • •Address translation formula multiplies row offset by the Number of Columns (U₂ - L₂ + 1).
  • •Natural reading order for raster displays, frame buffers, and standard image processing.
"Traverse row by row: advance column index rapidly to maximize CPU cache line re-use."
Column-Major

Column-Major Order (CMO)

⬇️
Dominant Architecture / DomainFortran, MATLAB, Julia, R, GNU Octave, BLAS/LAPACK
  • •Consecutive elements in memory share the same column: A[i][j] is immediately followed by A[i+1][j].
  • •Column index j advances large memory blocks; row index i advances unit word strides.
  • •Address translation formula multiplies column offset by the Number of Rows (U₁ - L₁ + 1).
  • •Native standard for linear algebra kernels (BLAS / LAPACK) originally developed in Fortran.
"Traverse column by column: advance row index rapidly to prevent cache-line thrashing."

🧊 Generalization to 3D and Multidimensional Arrays​

The principle of linearizing multidimensional coordinates extends recursively to any number of dimensions. Consider a Three-Dimensional (3D) Array:

A[L1…U1][L2…U2][L3…U3]A[L_1 \dots U_1][L_2 \dots U_2][L_3 \dots U_3]

Let the dimension spans (extents) be:

  • D1=U1−L1+1D_1 = U_1 - L_1 + 1 (Total 2D matrix slices / planes)
  • D2=U2−L2+1D_2 = U_2 - L_2 + 1 (Total rows per plane)
  • D3=U3−L3+1D_3 = U_3 - L_3 + 1 (Total columns per row)

3D Row-Major Order (Lexicographical Order)​

In 3D Row-Major Order, indices change slowest on the left (ii) and fastest on the right (kk). To locate element A[i][j][k]A[i][j][k]:

  1. Full Planes Skipped: (i−L1)(i - L_1) planes, where each plane contains D2×D3D_2 \times D_3 elements.
  2. Full Rows Skipped in Target Plane: (j−L2)(j - L_2) rows, where each row contains D3D_3 elements.
  3. Elements Skipped in Target Row: (k−L3)(k - L_3) elements.
📐3D Row-Major Addressing Formulaformula
Address(A[i][j][k])=B+W×[(i−L1)×D2×D3+(j−L2)×D3+(k−L3)]\text{Address}(A[i][j][k]) = B + W \times \Big[ (i - L_1) \times D_2 \times D_3 + (j - L_2) \times D_3 + (k - L_3) \Big]

3D Column-Major Order​

In 3D Column-Major Order, the leftmost index (ii) changes fastest and the rightmost index (kk) changes slowest:

  1. Full Hyperplanes Skipped: (k−L3)(k - L_3) slices, where each slice contains D1×D2D_1 \times D_2 elements.
  2. Full Columns Skipped in Target Slice: (j−L2)(j - L_2) columns, where each column contains D1D_1 elements.
  3. Elements Skipped in Target Column: (i−L1)(i - L_1) elements.
📐3D Column-Major Addressing Formulaformula
Address(A[i][j][k])=B+W×[(k−L3)×D1×D2+(j−L2)×D1+(i−L1)]\text{Address}(A[i][j][k]) = B + W \times \Big[ (k - L_3) \times D_1 \times D_2 + (j - L_2) \times D_1 + (i - L_1) \Big]

🏭 Real-World Production Context: High-Performance Computing & Cache Locality​

Understanding multi-dimensional array layout is a critical engineering requirement in scientific computing, machine learning, and systems architecture:

1. Loop Tiling & Order Invariant in Matrix Multiplication​

In standard matrix multiplication (C=A×BC = A \times B), the textbook loop order is i-j-k:

// Naive i-j-k Matrix Multiplication
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
for (int k = 0; k < N; k++) {
C[i][j] += A[i][k] * B[k][j]; // B[k][j] causes Stride-N cache misses!
}
}
}

In the inner loop, accessing B[k][j] advances the row index k while holding column j constant. In Row-Major C, this causes a stride of N×4N \times 4 bytes per inner iteration, stalling the pipeline on memory fetches.

By simply swapping the two inner loops to i-k-j:

// Optimized i-k-j Matrix Multiplication (Cache-Friendly)
for (int i = 0; i < N; i++) {
for (int k = 0; k < N; k++) {
int r = A[i][k]; // Invariant in innermost loop
for (int j = 0; j < N; j++) {
C[i][j] += r * B[k][j]; // Both C and B advance with Stride-1!
}
}
}

Both C[i][j] and B[k][j] now iterate along columns with Stride-1 contiguous memory access. This single change accelerates execution by 500%500\% to 1200%1200\% on large matrices without modifying the algorithmic complexity!

2. Zero-Copy Tensor Transposition in PyTorch and NumPy​

In deep learning frameworks, calling .transpose() or .T on a tensor does not physically copy or rearrange matrix elements in RAM. Instead, PyTorch simply swaps the stride multipliers in the tensor's internal Dope Vector (Array Descriptor) and sets a non_contiguous flag. The operation executes in instantaneous O(1)\mathcal{O}(1) time.


📐 Numerical Applications & Worked Examples​

Problem 1: Standard 1-Based 2D Array in Row-Major Order​

Problem Statement:
Let AA be a two-dimensional array declared as:

A[1…10][1…15] of 4-byte integersA[1 \dots 10][1 \dots 15] \text{ of 4-byte integers}

The array is stored in Row-Major Order starting at Base Address B=1000B = 1000, and each integer consumes W=4W = 4 bytes. Compute the exact physical byte address of element A[4][6]A[4][6].

Step-by-Step Solution:

  1. Extract Dimension Parameters:

    • Row lower and upper bounds: L1=1,U1=10  ⟹  M=10−1+1=10 rowsL_1 = 1, U_1 = 10 \implies M = 10 - 1 + 1 = 10\text{ rows}
    • Column lower and upper bounds: L2=1,U2=15  ⟹  N=15−1+1=15 columnsL_2 = 1, U_2 = 15 \implies N = 15 - 1 + 1 = 15\text{ columns}
    • Base Address: B=1000B = 1000; Element Size: W=4W = 4 bytes
    • Target Coordinates: i=4,j=6i = 4, j = 6
  2. Calculate Preceding Rows and Elements:

    • Number of complete rows before row 4: i−L1=4−1=3 full rowsi - L_1 = 4 - 1 = 3\text{ full rows}
    • Elements contained in 3 full rows: 3×N=3×15=45 elements3 \times N = 3 \times 15 = 45\text{ elements}
    • Elements before column 6 in the current row: j−L2=6−1=5 elementsj - L_2 = 6 - 1 = 5\text{ elements}
    • Total preceding elements: 45+5=50 elements45 + 5 = 50\text{ elements}
  3. Compute Physical Byte Address:

    Address(A[4][6])=B+W×[(i−L1)×N+(j−L2)]=1000+4×50=1000+200=1200\begin{aligned} \text{Address}(A[4][6]) &= B + W \times \Big[ (i - L_1) \times N + (j - L_2) \Big] \\ &= 1000 + 4 \times 50 \\ &= 1000 + 200 = \mathbf{1200} \end{aligned}

Problem 2: Arbitrary Negative Lower Bounds in Both RMO and CMO​

Problem Statement:
An array is declared with non-standard negative index boundaries:

A[5…15][−8…8]A[5 \dots 15][-8 \dots 8]

Base address B=800B = 800, and each element occupies W=4W = 4 memory bytes.

  1. Find the physical memory address of element A[8][5]A[8][5] assuming Row-Major Order.
  2. Find the physical memory address of element A[8][5]A[8][5] assuming Column-Major Order.

Step-by-Step Solution:

  1. Calculate Dimension Capacities:

    • Rows M=U1−L1+1=15−5+1=11 rowsM = U_1 - L_1 + 1 = 15 - 5 + 1 = 11\text{ rows}
    • Columns N=U2−L2+1=8−(−8)+1=8+8+1=17 columnsN = U_2 - L_2 + 1 = 8 - (-8) + 1 = 8 + 8 + 1 = 17\text{ columns}
    • Target coordinates: i=8,j=5i = 8, j = 5
  2. Part 1: Row-Major Order (RMO):

    • Full preceding rows: i−L1=8−5=3i - L_1 = 8 - 5 = 3
    • Elements in preceding rows: 3×N=3×17=513 \times N = 3 \times 17 = 51
    • Elements before target in current row: j−L2=5−(−8)=13j - L_2 = 5 - (-8) = 13
    • Total preceding elements: 51+13=6451 + 13 = 64
    Address(A[8][5])RMO=800+4×64=800+256=1056\text{Address}(A[8][5])_{\text{RMO}} = 800 + 4 \times 64 = 800 + 256 = \mathbf{1056}
  3. Part 2: Column-Major Order (CMO):

    • Full preceding columns: j−L2=5−(−8)=13j - L_2 = 5 - (-8) = 13
    • Elements in preceding columns: 13×M=13×11=14313 \times M = 13 \times 11 = 143
    • Elements before target in current column: i−L1=8−5=3i - L_1 = 8 - 5 = 3
    • Total preceding elements: 143+3=146143 + 3 = 146
    Address(A[8][5])CMO=800+4×146=800+584=1384\text{Address}(A[8][5])_{\text{CMO}} = 800 + 4 \times 146 = 800 + 584 = \mathbf{1384}

Problem 3: Double Matrix Transposition Loop Invariant​

Problem Statement:
Let AA be a square matrix of size n×nn \times n. Analyze the state of matrix AA after executing the following algorithm:

int C = 100;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
int Temp = A[i][j] + C;
A[i][j] = A[j][i];
A[j][i] = Temp - C;
}
}

Step-by-Step Solution:

  1. Analyze the Loop Body Mutation:

    • For any pair (i,j)(i, j): Temp=A[i][j]+C\text{Temp} = A[i][j] + C A[i][j]←A[j][i]A[i][j] \leftarrow A[j][i] A[j][i]←Temp−C=(A[i][j]+C)−C=A[i][j]A[j][i] \leftarrow \text{Temp} - C = (A[i][j] + C) - C = A[i][j]
    • The loop body performs a standard swap between A[i][j]A[i][j] and its symmetric counterpart A[j][i]A[j][i].
  2. Identify the Symmetric Double-Swap Trap:

    • Both outer and inner loops iterate through the entire matrix from 11 to nn.
    • When i=1,j=2i = 1, j = 2, elements A[1][2]A[1][2] and A[2][1]A[2][1] are swapped.
    • When the loops reach i=2,j=1i = 2, j = 1, elements A[2][1]A[2][1] and A[1][2]A[1][2] are swapped a second time, returning them to their exact original locations!
    • Along the main diagonal (i=ji = j), swapping an element with itself leaves it unchanged.
  3. Conclusion: Every off-diagonal element undergoes two successive transpositions:

    (AT)T=A(A^T)^T = A

    The matrix remains completely unchanged in its initial state.


🎯 Exam & Interview Pitfall Check​

Core Conceptual Questions

Q1: Why does Row-Major Order yield dramatic performance gains for row-wise inner loops compared to column-wise inner loops in C?
Explanation: In Row-Major Order, elements on the same row with consecutive column indices (A[i][j]A[i][j] and A[i][j+1]A[i][j+1]) reside in adjacent physical memory bytes. When the CPU fetches A[i][j]A[i][j], hardware prefetchers load the entire 64-byte cache line containing up to 16 four-byte integers into L1 cache. Consecutive inner-loop reads achieve instant O(1)\mathcal{O}(1) cache hits. Conversely, iterating across columns jumps N×4N \times 4 bytes per step, causing cache line thrashing and RAM bus stalls.

Q2: An array A[1…8][1…12]A[1 \dots 8][1 \dots 12] has base address 2000 and element size 2 bytes. What is the address of A[5][7]A[5][7] in Column-Major Order?
Explanation:

  • Total rows: M=8−1+1=8M = 8 - 1 + 1 = 8
  • Preceding columns: j−L2=7−1=6j - L_2 = 7 - 1 = 6
  • Elements in full columns: 6×M=6×8=486 \times M = 6 \times 8 = 48
  • Elements in current column: i−L1=5−1=4i - L_1 = 5 - 1 = 4
  • Total elements: 48+4=5248 + 4 = 52
  • Address=2000+2×52=2000+104=2104\text{Address} = 2000 + 2 \times 52 = 2000 + 104 = \mathbf{2104}.

Q3: How many total elements exist in a 3D array defined as A[2…6][−3…3][1…5]A[2 \dots 6][-3 \dots 3][1 \dots 5]?
Explanation:

  • D1=6−2+1=5D_1 = 6 - 2 + 1 = 5 slices
  • D2=3−(−3)+1=7D_2 = 3 - (-3) + 1 = 7 rows per slice
  • D3=5−1+1=5D_3 = 5 - 1 + 1 = 5 columns per row
  • Total Elements=D1×D2×D3=5×7×5=175 elements\text{Total Elements} = D_1 \times D_2 \times D_3 = 5 \times 7 \times 5 = \mathbf{175\text{ elements}}.
Common Interview Traps
  • Multiplying by Rows instead of Columns in RMO: In Row-Major Order, a common error is multiplying the row offset by the number of rows MM: (i−L1)×M(i - L_1) \times M. Always remember: each row contains NN columns (elements). To skip a row, you must skip NN elements. In RMO, multiply by Columns NN; in CMO, multiply by Rows MM.
  • Sign Errors in Negative Bounds: When a lower bound is negative (L2=−8L_2 = -8), compute column count as U2−L2+1=8−(−8)+1=17U_2 - L_2 + 1 = 8 - (-8) + 1 = 17. Writing 8−8+1=18 - 8 + 1 = 1 causes total failure in address translation.
  • Assuming RMO Across All Languages: Never assume Row-Major layout unless specified. Languages like Fortran, MATLAB, Julia, and R use Column-Major Order. Passing an RMO array to a legacy BLAS/LAPACK routine without transposition results in an implicit matrix transposition.

🚀 Navigation & Next Steps​

🚀 Level Up Your Engineering Mindset

Never Study in Isolation. Join Binary Dose.

Connect with fellow engineers, clear conceptual doubts, and get 2 visual breakdowns & engineering mental models daily across our community channels.

Discord
Official Hub

Discord Community

Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.

Join Discord Server→
⚡
Daily Knowledge Drops

Daily Visual Deep-Dives

Bite-sized system design schematics, core OS internals, and DSA intuition served right into your feeds every single day.

💡Help keep Binary Dose free for students, or share your articles and notes.