pointers-memory · intermediate · ~15 min

2D matrix stride extraction from flat buffer

Perform row-major stride arithmetic and construct row-pointer vectors from flat memory buffers.

Challenge

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.

Your Task

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);

Rules

  1. In get_matrix_elem:
    • If flat == NULL, out_val == NULL, r >= rows, or c >= cols, return -1.
    • Store the element at row r and column c into *out_val and return 0.
  2. In init_row_pointers:
    • Populate row_ptrs[r] to point directly to the start of row r (flat + r * cols) for each 0 <= r < rows.
    • This allows indexing via row_ptrs[r][c] directly.

Input format

flat: 1D array of rows * cols ints; r, c: row and col coordinates; row_ptrs: array of row pointers.

Output format

get_matrix_elem returns 0 on success, -1 on bounds error.

Constraints

Row-major layout. Stride equals cols * sizeof(int).

Starter code

#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;
}

Common mistakes

Confusing rows and cols in stride calculation (using r * rows instead of r * cols).

Edge cases to handle

r == rows - 1 and c == cols - 1 (last element); r >= rows returns -1; NULL pointers.

Background lessons

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