data-structures · intermediate · ~15 min

Flatten a 2D array to 1D (row-major)

Manual row-major addressing and the equivalence with linear iteration.

Challenge

Copy a 2D grid into a 1D buffer using row-major addressing.

Task

Implement void flatten_row_major(const int *src, int rows, int cols, int *dst) that copies a rows x cols grid — stored contiguously in src, one row after another — into the 1D buffer dst in row-major order. Write the explicit double loop using [i * cols + j] indexing rather than a single memcpy.

Input

  • src: a read-only block of rows * cols ints, laid out row by row.
  • rows, cols: the grid dimensions.
  • dst: a writable buffer with room for rows * cols ints.

Output

Nothing returned; dst holds the same values in the same order as src.

Example

src = {1,2,3, 4,5,6}    (2x3 grid)
flatten_row_major(src, 2, 3, dst)
dst   ->   {1, 2, 3, 4, 5, 6}

Edge cases

  • rows == 0 or cols == 0: nothing to copy (must not crash, even if src is NULL).
  • A single-element grid.
  • Non-square grids (rows != cols).

Rules

  • Use the explicit i * cols + j indexing form rather than a bulk memcpy.

Why this matters

Real C code rarely uses int ** for matrices because pointer indirection trashes the cache. Storing a 2D grid in a single contiguous block and indexing [i * cols + j] is the standard high-performance layout (used by NumPy, BLAS, image libraries, etc.).

Input format

src: read-only block of rows*cols ints (row by row); rows; cols; dst: buffer of rows*cols ints.

Output format

Nothing returned; dst holds the same values in the same order.

Constraints

Use the explicit i * cols + j indexing form (don't just memcpy).

Starter code

void flatten_row_major(const int *src, int rows, int cols, int *dst) { /* TODO */ }

Common mistakes

Mixing up i and j (column-major addressing). Off-by-one on the outer loop. Mismatched destination size.

Edge cases to handle

0 rows; 0 cols; 1x1; non-square (rows != cols).

Complexity

O(rows * cols).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.