← 👉 Pointers & Arrays
Subtopic 4 of 5

3.4Two-dimensional arrays (row-major)

The idea

A 2-D array is a 1-D array of rows. In memory it is laid out row after row (row-major), so a[i][j] sits at offset i × columns + j.

Think of it like this: A bookshelf: rows are shelves, but the books are really lined up in one long line, shelf after shelf.

Why it exists

Pointer expressions such as *(*(a + i) + j) and page-fault counts for column-wise traversal both follow from row-major layout.

How it works

  1. a[i] is the i-th row, an array of C ints.
  2. a + 1 skips a whole row (C elements); *(a + 1) is that row.
  3. *(a + i) + j points to a[i][j]; dereference once more to read it.
  4. Walking down a column jumps C elements each step, which is bad for cache and paging.

Worked example: *(*(a + **a + 2) + 3) with a[4][5]

**a = a[0][0] = 1. So a + 1 + 2 = a + 3 is row 3, and adding 3 and dereferencing gives a[3][3] = 19.

Now play with it

  • →In the lab try *(*(a + 1) + 2) and &a[2][3] − &a[0][0] (it is 11).
  • →Run the GATE 2020 program to see 19.

a is 3 rows of 4 ints, stored row after row. a + 1 skips a whole ROW (4 ints).

type of the expressionint
value7
Memory (one box per element, address below)
1
a[0][0]
@100
2
a[0][1]
@101
3
a[0][2]
@102
4
a[0][3]
@103
5
a[1][0]
@104
6
a[1][1]
@105
7
a[1][2]
@106
8
a[1][3]
@107
9
a[2][0]
@108
10
a[2][1]
@109
11
a[2][2]
@110
12
a[2][3]
@111

Gold = the object the expression names. Blue = the element a pointer result points to. Each box stands for one element; real addresses grow by sizeof(element).

**a is a[0][0] = 1, so a + 1 + 2 is a + 3, the row at index 3. Adding 3 to that row and dereferencing gives a[3][3].

step 1 of 4
1#include <stdio.h>
2int main() {
3 int a[4][5] = {{1, 2, 3, 4, 5},
4 {6, 7, 8, 9, 10},
5 {11, 12, 13, 14, 15},
6 {16, 17, 18, 19, 20}};
7 printf("%d\n", *(*(a + **a + 2) + 3));
8 return 0;
9}

The gold line is the statement about to run.

Call stack (top first)
main()
no variables yet
Output

Check yourself

For int a[3][4] with base address 2000 and 4-byte ints, the address of a[2][1] is

Remember: a[i][j] ≡ *(*(a + i) + j) at offset (i·C + j) elements; a + 1 skips a row.
Exam notes (the dense version)

int a[R][C] is R arrays of C ints stored row after row: the address of a[i][j] is base + (i·C + j)·sizeof(int). a decays to a pointer to a row (int (*)[C]), so a + i skips whole rows, *(a + i) is row i, and *(*(a + i) + j) is a[i][j]. Initialisers may omit inner braces: they fill in row-major order.

Previous year questions: Pointers & Arrays (11)

PYQs are grouped by topic, so this is the full set for Pointers & Arrays; try the ones that match this subtopic. Open all 11 on the topic page.