pointers-memory · intermediate · ~15 min
Perform row-major stride arithmetic and construct row-pointer vectors from flat memory buffers.
High-performance 2D matrices and images are stored in a single contiguous 1D memory array to ensure cache locality. Programmers calculate row-major strides using row * cols + col.
Implement:
int get_matrix_elem(const int *flat, size_t rows, size_t cols, size_t r, size_t c, int *out_val);
void init_row_pointers(const int *flat, size_t rows, size_t cols, const int **row_ptrs);
get_matrix_elem:flat == NULL, out_val == NULL, r >= rows, or c >= cols, return -1.r and column c into *out_val and return 0.init_row_pointers:row_ptrs[r] to point directly to the start of row r (flat + r * cols) for each 0 <= r < rows.row_ptrs[r][c] directly.flat: 1D array of rows * cols ints; r, c: row and col coordinates; row_ptrs: array of row pointers.
get_matrix_elem returns 0 on success, -1 on bounds error.
Row-major layout. Stride equals cols * sizeof(int).
#include <stddef.h>
/* Retrieve element at (r, c) from flat matrix of size rows x cols.
Store in *out_val and return 0, or -1 on bounds/null error. */
int get_matrix_elem(const int *flat, size_t rows, size_t cols, size_t r, size_t c, int *out_val) {
(void)flat; (void)rows; (void)cols; (void)r; (void)c; (void)out_val;
return -1;
}
/* Initialize row_ptrs array such that row_ptrs[r] points to row r of flat. */
void init_row_pointers(const int *flat, size_t rows, size_t cols, const int **row_ptrs) {
(void)flat; (void)rows; (void)cols; (void)row_ptrs;
}
Confusing rows and cols in stride calculation (using r * rows instead of r * cols).
r == rows - 1 and c == cols - 1 (last element); r >= rows returns -1; NULL pointers.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.