Huy Doan - 1 year ago 88

C Question

I have a 2D matrix

`matrix[m][n];`

I know that matrix is a double pointer with type

`int**`

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