Sub topic 2
Arrays: contiguous memory and index arithmetic
This chapter assumes you can write loops and functions in C, Java, or Python, know what a pointer or object reference is, and have seen Big-O notation at an introductory level. You will learn how an array is laid out in memory, how the address of any element is computed, and why that layout gives constant-time access. GATE CS asks address-calculation questions often, so the formulas here are worth knowing exactly.
What an array is
An array is a fixed-size collection of elements of the same type, stored one after another in a single block of contiguous memory. Contiguous means there are no gaps between elements. Because every element has the same size, the position of any element can be computed from the position of the first one.
Two facts define the structure:
- All elements have the same type, so each occupies the same number of bytes, called the element size
w. - The elements sit at consecutive addresses, so element
i + 1starts exactlywbytes after elementi.
The address of the first element is the base address. In the diagram the base address is 1000 and w = 4.
Address arithmetic for one-dimensional arrays
If the lowest valid index is LB (lower bound), the address of element i is:
address(A[i]) = base + (i - LB) * wIn C, Java, and Python the lower bound is 0, so the formula simplifies to base + i * w. GATE questions sometimes use other lower bounds, for example an array declared as A[-3..10] or A[1..100]. Always subtract the lower bound first.
The number of elements in an array with bounds LB..UB is UB - LB + 1. Forgetting the + 1 is a common error.
Worked example. An array A[5..20] stores 2-byte elements with base address 3000. Where is A[12]?
- Offset in elements:
12 - 5 = 7. - Offset in bytes:
7 * 2 = 14. - Address:
3000 + 14 = 3014.
Why access is O(1)
Finding A[i] takes one subtraction, one multiplication, and one addition, no matter how large the array is or how large i is. The machine then reads the memory at that address directly. The cost does not depend on n, so access is O(1). This property is called random access.
The same arithmetic explains why arrays are the base for other structures in this tutorial. Stacks, circular queues, and binary heaps all store their data in an array and use index arithmetic to move around, as the later chapters show.
Two-dimensional arrays
Memory is one-dimensional, so a 2-D array must be flattened. There are two standard orders.
- Row-major order stores row 0 completely, then row 1, and so on. C, C++, Java (as arrays of arrays), and Python lists of lists follow this idea.
- Column-major order stores column 0 completely, then column 1, and so on. Fortran and MATLAB use it.
For an array with R rows and C columns, and lower bounds of 0:
| Order | Address of `A[i][j]` |
|---|---|
| Row-major | `base + (i * C + j) * w` |
| Column-major | `base + (j * R + i) * w` |
For general bounds A[r1..r2][c1..c2], let R = r2 - r1 + 1 and C = c2 - c1 + 1. Then:
- Row-major:
base + ((i - r1) * C + (j - c1)) * w - Column-major:
base + ((j - c1) * R + (i - r1)) * w
In row-major order, C is the number of elements in one row, so skipping i rows moves you past i * C elements. In column-major order, skipping j columns moves you past j * R elements. Mixing up R and C is the most frequent mistake.
Worked example. A[1..4][1..5] holds 4-byte elements, stored row-major from base 500. Find the address of A[3][2].
R = 4,C = 5.- Row offset:
(3 - 1) * 5 = 10elements. - Column offset:
2 - 1 = 1element. - Total:
11 * 4 = 44bytes. - Address:
500 + 44 = 544.
The same element in column-major order: (2 - 1) * 4 + (3 - 1) = 6 elements, so 500 + 24 = 524.
You can check the row-major formula in code:
def row_major_address(base, w, r1, c1, num_cols, i, j):
"""Address of A[i][j] for an array with lower bounds (r1, c1)."""
return base + ((i - r1) * num_cols + (j - c1)) * w
def col_major_address(base, w, r1, c1, num_rows, i, j):
return base + ((j - c1) * num_rows + (i - r1)) * w
print(row_major_address(500, 4, 1, 1, 5, 3, 2)) # 544
print(col_major_address(500, 4, 1, 1, 4, 3, 2)) # 524Arrays and pointers in C
In C, the expression A[i] is defined as *(A + i). Adding i to a pointer moves it by i elements, not i bytes, so the compiler multiplies by w for you. This is the same formula with LB = 0. It is also why C does not check bounds: A[i] with a bad i just reads whatever memory sits at that address.
#include <stdio.h>
int main(void) {
int a[5] = {10, 20, 30, 40, 50};
int *p = a; /* p points to a[0] */
printf("%d %d\n", a[3], *(p + 3)); /* 40 40 */
printf("%ld\n", (long)((char *)&a[3] - (char *)&a[0])); /* 12 on 4-byte int */
return 0;
}Costs and limits of the layout
Contiguity has consequences beyond fast access.
- Size is fixed at creation. A static array cannot grow in place, because the memory after it may belong to something else. Growing means allocating a new block and copying, which costs O(n).
- Space is exactly
n * wbytes, with no per-element pointer overhead. A linked list pays extra for each node's pointer. - Sequential scans are fast on real hardware because neighbouring elements share cache lines. This is a practical advantage that Big-O does not show.
- Memory must be available as one block. A large array can fail to allocate even when the total free memory is enough.
Common errors
- Off-by-one in bounds: the valid indices of an array of size
nwithLB = 0are0..n-1. Indexnis out of range. - Ignoring the lower bound in an address formula.
- Using the wrong order (row-major versus column-major) when the question names one.
- Confusing element offset with byte offset: multiply by
wonce, at the end. - Treating Python lists as raw contiguous arrays of values. A Python list is contiguous, but it stores references to objects, not the values themselves.
Summary of costs
| Operation | Cost for an array of `n` elements |
|---|---|
| Access by index | O(1) |
| Space | O(n), exactly `n * w` bytes |
| Grow beyond capacity | O(n), allocate and copy |
Search, insertion, and deletion are covered in the next chapter.
Exercise
A 2-D array B[0..9][0..19] stores 8-byte elements in row-major order with base address 2000. What is the address of B[4][7]? What is it if the array is stored in column-major order?
Show answer
Here R = 10 and C = 20. Row-major: (4 * 20 + 7) * 8 = 87 * 8 = 696, so the address is 2000 + 696 = 2696. Column-major: (7 * 10 + 4) * 8 = 74 * 8 = 592, so the address is 2000 + 592 = 2592.
Exercise
An array A[-5..14] has 4-byte elements and base address 800. How many elements does it hold, and what is the address of A[0]?
Show answer
The count is 14 - (-5) + 1 = 20 elements. The offset of A[0] is (0 - (-5)) * 4 = 20 bytes, so its address is 800 + 20 = 820.
Exercise
Why is access by index O(1) for an array but O(n) for a singly linked list?
Show answer
In an array, the address of element i is computed directly as base + (i - LB) * w, which takes a fixed number of arithmetic steps. In a singly linked list, nodes are scattered in memory and each node only stores the address of the next one, so reaching position i requires following i pointers from the head.