Sub topic 2
Arrays: Contiguous Memory and Index Arithmetic
Prerequisites and the working model
Assume you know loops, functions, references or pointers, and introductory Big-O notation. An array is a fixed-size sequence whose elements occupy consecutive memory locations. Every element has the same type and size.
If an array starts at address \(B\), each element uses \(w\) bytes, and indexing starts at \(L\), the address of element \(A[i]\) is:
\[ \operatorname{address}(A[i]) = B + (i-L)w \]
Most programming languages use zero-based indexing, so \(L=0\):
\[ \operatorname{address}(A[i]) = B + iw \]
The index is converted directly into an offset. Therefore, accessing A[i] takes constant time, or \(O(1)\).
#include <stdio.h>
int main(void) {
int a[] = {10, 20, 30, 40};
int i = 2;
printf("value = %d\n", a[i]);
printf("offset in elements = %td\n", &a[i] - &a[0]);
printf("same value through a pointer = %d\n", *(a + i));
return 0;
}In C, a + i points to the element at index i. Pointer arithmetic automatically moves by i * sizeof(int) bytes, rather than by only i bytes.
Why access is fast
The array does not need to inspect earlier elements. It calculates the target address immediately. This differs from a singly linked list, where reaching the element at position i requires following i links.
| Operation | Array cost | Reason |
|---|---|---|
| Access by index | \(O(1)\) | Direct address calculation |
| Search in an unsorted array | \(O(n)\) | Elements may be checked one by one |
| Insert at the beginning | \(O(n)\) | Existing elements shift right |
| Delete at the beginning | \(O(n)\) | Remaining elements shift left |
Appending can be \(O(1)\) when unused capacity exists. In a dynamically growing array, an occasional resize copies all elements, but the average cost per append is usually \(O(1)\), called amortized constant time.
Index arithmetic and layout
For a two-dimensional array stored in row-major order, rows are placed one after another. For an array with C columns, zero-based element A[r][c] has the linear offset:
\[ rC+c \]
For example, in a 3-column array, A[2][1] has offset \(2(3)+1=7\).
Common errors
- Confusing an index with a byte offset. The byte offset is
i * w. - Using
A[n]for an array withnelements. The last valid index isn - 1. - Assuming insertion is constant time merely because access is constant time.
- Forgetting that a fixed array cannot grow without allocating another region.
Exercise
An integer array starts at address 1000, each integer uses 4 bytes, and indexing starts at zero. What is the address of A[6]?
Show answer
1024, because the address is 1000 + 6 × 4.