Huy Doan Huy Doan - 1 year ago 106
C Question

Double pointer arithmetic

I have a 2D matrix


I know that matrix is a double pointer with type
. I would like to obtain a double pointer pointing to a submatrix of the original matrix. For example, I want the submatrix to start for cell (1,1). How do I get such a double pointer from the original matrix[m][n]?

Answer Source

A matrix defined as 2D array of constant size:

    Int matrix [m][n];

is stored as m contiguous blocks of n elements. You can therefore imagine this technically as a flat sequence of m*n elements in memory. You can use pointer arithmetic to find the start of a row, or to find a specific element. But you can't locate a submatrix int that way.

The "double" pointer:

    int **pmatrix;

obeys a different logic: it is a pointer to a pointer and wors as an array of m pointers pointing at lines of n consecutive elements. so your elements are not necessarily consecutive. You can use pointer arithmetic and indirection to locate the start of a row or a specific item. But again this can't adress a submatrix.

Both matrix and pmatrix can be used with 1D or 2D indexing, but the compiler generates different code to address the elements.

For getting submatrixes you have to make iterations to find the right elements, using vertical and horizontal offsets, but you can't imagine to pass somehow a pointer to the submatrix if you don't copy the right elements in a new matrix of target's size

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download