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
- a[i] is the i-th row, an array of C ints.
- a + 1 skips a whole row (C elements); *(a + 1) is that row.
- *(a + i) + j points to a[i][j]; dereference once more to read it.
- 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).
Memory (one box per element, address below)
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].
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)
Output
Check yourself
For int a[3][4] with base address 2000 and 4-byte ints, the address of a[2][1] is
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.