Simvik

Index a matrix through a pointer

Read an element of a 2-D array given only a pointer to its first element. An easy embedded C problem (Pointers), run and graded in the browser.

easy · Pointers · arrays · pointer-arithmetic

A two-dimensional array is stored row after row in one block of memory. A function that receives only a pointer to the first element has to compute positions itself.

Return the element at row row, column col of a matrix with cols columns.

Starter code

int32_t matrix_get(const int32_t *m, size_t cols, size_t row, size_t col) {
  // The matrix is stored row by row starting at m.
  return 0;
}

Example tests

Last element of a 2 x 3 matrix

int32_t m[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
printf("%d\n", matrix_get(&m[0][0], 3, 1, 2));

Expected output:

6

First row

int32_t m[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
printf("%d\n", matrix_get(&m[0][0], 3, 0, 1));

Expected output:

2

Learn it first

  • Pointers · Addresses, arithmetic, const, void pointers and object lifetime.

More Pointers problems