basics · beginner · ~15 min
Convert 2-D indices to a 1-D offset (r*cols + c).
A 2-D matrix stored in a flat 1-D array — read one element by its row and column.
A rows x cols matrix is stored row-major in a flat array m (row 0 first, then row 1, and so on). Implement int flat_get(const int *m, int cols, int r, int c) that returns the element at row r, column c. The offset of (r, c) in the flat array is r*cols + c. No main — the grader calls it.
A flat array m, the column count int cols, and the target indices int r and int c (both in range).
Returns the element at (r, c), as an int.
m = {1,2,3, 4,5,6} (2 rows x 3 cols)
flat_get(m, 3, 0, 0) -> 1
flat_get(m, 3, 1, 2) -> 6
flat_get(m, 3, 0, 2) -> 3
A flat array m, the column count int cols, and indices int r, int c.
The element at (r, c), as an int.
Row-major layout; offset is r*cols + c.
int flat_get(const int *m, int cols, int r, int c) {
/* TODO */
return 0;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.