student@ubuntu:~$
Topic Week 6 2 min overview

2D Arrays

Rows and columns, row-major memory layout, and why pointer arithmetic still works

In a nutshell

A 2D array in C is an array of arrays. int grid[3][4] is three rows of four ints each, stored contiguously in memory in row-major order (first all of row 0, then all of row 1, then all of row 2). You index with grid[r][c]. Nested for loops over rows and columns is the standard iteration pattern.

Under the hood, grid[r][c] is pointer arithmetic: *(grid + r * COLS + c). That is why passing a 2D array to a function takes care: the function needs to know the column count at compile time (so the arithmetic is correct), so the parameter declaration is int grid[][COLS] or int (*grid)[COLS].

Why it matters

Image processing, game boards, matrix operations, neural-network layers, grid-based simulations, terrain maps — anywhere a problem has two-dimensional structure, 2D arrays are the natural representation. For Lab 8 (grid-based) and beyond, you need to be fluent at nested iteration and at passing 2D arrays to helper functions.

Key takeaways

  • Row-major storage. grid[0][0], grid[0][1], ..., grid[0][C-1], grid[1][0], ... in contiguous memory.
  • Indexing is pointer arithmetic. grid[r][c] is *((int *)grid + r * COLS + c).
  • Column count is part of the type. A function that takes a 2D array needs to know COLS at compile time: void print_grid(int grid[][4], int rows).
  • Nested for loops are the iteration pattern: outer over rows, inner over columns.
  • Passing an “array of rows” through a pointer-to-row: int (*grid)[COLS]. Read right-to-left: pointer to array of COLS ints.
  • For runtime-sized grids, flatten to 1D and compute offsets yourself, or use an array of pointers to separately-allocated rows (the “ragged array” pattern). Both appear in week 7.

Lessons in this topic

Lesson What it covers
2D Arrays Declaring, initializing, iterating, passing to functions, the row-major memory layout

Practice and deep dives

Practice this topic: Arrays drill, or browse the practice gallery.

What comes next

Week 7 moves to generic programming. void * is the escape hatch C provides for “a pointer to anything,” and it is the foundation for qsort, generic containers, and every library function that needs to work on arbitrary types.