data-structures · intermediate · ~15 min
Manual row-major addressing and the equivalence with linear iteration.
Copy a 2D grid into a 1D buffer using row-major addressing.
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.
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.Nothing returned; dst holds the same values in the same order as src.
src = {1,2,3, 4,5,6} (2x3 grid)
flatten_row_major(src, 2, 3, dst)
dst -> {1, 2, 3, 4, 5, 6}
rows == 0 or cols == 0: nothing to copy (must not crash, even if src is NULL).i * cols + j indexing form rather than a bulk memcpy.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.).
src: read-only block of rows*cols ints (row by row); rows; cols; dst: buffer of rows*cols ints.
Nothing returned; dst holds the same values in the same order.
Use the explicit i * cols + j indexing form (don't just memcpy).
void flatten_row_major(const int *src, int rows, int cols, int *dst) { /* TODO */ }
Mixing up i and j (column-major addressing). Off-by-one on the outer loop. Mismatched destination size.
0 rows; 0 cols; 1x1; non-square (rows != cols).
O(rows * cols).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.