# Subscript address translation formula of two dimensional array a [M] [n] with row priority and column priority

2021-07-20 00:56:00

Let's set up a two-dimensional array A[m][n] Store by row first , Each element accounts for p Bytes ,

be Loc(i, j) The address for (i * n + m) * p, The first i Yes, there is i That's ok , Each row has n Elements , add The first i OK j Elements , So the address by (i * n + m) * p,

1. if j From the subscript 1 Start , be Loc(i, j) = (i * n + j - 1)

The first i Yes The first j Elements , In the i In line There is only j  - 1 Elements ,

2. if i From the subscript 1 Start , be Loc(i, j) = ((i - 1) * n + j）

3. if i, j All from Subscript 1 Start , be Loc(i, j) = ((i - 1) * n + j - 1)

If the array is stored in columns first ,

be Loc(i, j) by   (j * m + i) * p, The first j  In front of the column is j Column , Each column has m Elements , add The first j Column i Elements , So for (j * m + i) * p

1. if j From the subscript 1 Start , be Loc(i, j) = ((j - 1) * m + i);

because The first j In front of the column is just   (j - 1) Column

2. if i From the subscript 1 Start , be Loc(i, j) = (j * m + i - 1）

The first i The first element is actually just i - 1 Elements

3. if i, j All from Subscript 1 Start , be Loc(i, j) = ((j - 1) * n + i - 1)

### summary ：

Line by line priority Loc(i, j) = (i * n + j) * p, Priority by column Loc(i, j) = (j * m + i) * p, Line subscript 1 Start   i Just subtract one , Column from subscript 1 Start , j Just subtract one

https://chowdera.com/2021/05/20210530100648278i.html