2D array calculation formula

Suppose the address for A[10][10] is 40,000, double takes 16 bytes, and byte addressing is used, what are the addresses for A[40, 50] ?

I'm just trying to calculate a simple point in 2D and just want to double check that I have connected the correct values ​​in the equation

 BA + [n * (i - LBR) + (j - LBC)] * w 40000 +[10*(40-0)+(50-0)]*16 40000+[10*(40)+(50)]*16 40000+[900]*16 = 54400 

Did I apply the formula here correctly? I was not sure that I connected the correct values?

+6
source share
3 answers

In C ++, a 2d array is just an array of arrays, so in A memory is used to

 A[ 0][ 0] A[ 0][ 1] A[ 0][ 2] ... A[ 0][99] A[ 1][ 0] A[ 1][ 1] A[ 1][ 2] ... A[ 1][99] ... A[99][ 0] A[99][ 1] A[99][ 2] ... A[99][99] 

where each line just follows the previous one in memory.

The address in the at (row, col) element is

 (unsigned char *)(&A[0][0]) + (row*row_size + col) * element_size 

In your case, you know that the element you are looking for is 30 lines below and 40 elements to the right of this element, so the address will be

 40000 + ((40 - 10)*100 + (50 - 10)) * 16 

total 88640.

You can get the same result by subtracting the relative address of the element (10, 10) from the given address (to find the beginning of the array), and then adding the relative address (40, 50) .

+4
source

The answer depends on whether you use the basic row order or column order. In the main ordering order, the data is stored in a row. When arranging columns, data is stored in a column. Consider the following 2D array, which will be stored in memory,

  11 22 33 44 55 66 77 88 99 

In the main ordering of strings, elements are stored contiguously as 11,22,33,44,55,66,77,88,99 . When arranging columns, the elements are stored adjacent to 11,44,77,22,55,88,33,66,99 .

+2
source

The value of the following equation:

 BA + [n * (i - LBR) + (j - LBC)] * w 

If you have an array A [n] [n] and you know the address of the record A [LBR] [LBC] as BA, then the address A [i] [j] can be calculated as follows. Assuming n = 6,

 00 01 02 03 04 05 10 11 12 13 14 15 20 21 22 23 24 25 30 31 32 33 34 35 40 41 42 43 44 45 50 51 52 53 54 55 

Here, suppose we know the address A [2,1] = 1000. We need to calculate the address A [4,2]. Now, to reach [4.2] from [2.1], how many records will we need to travel? Of course, as @Deepu points out, we can do this in two ways: either move in rows or in columns. It can be seen from the equation that row row selection was selected.

 22 to 25 (4) 30 to 35 (6) 40 to 42.(3) = 13 entries. 

Therefore, the address A [4,2] = 1000 + 13 * (numOfbytes per entry)

To check using the equation,

 i - LBR = 4 - 2 = 2. j - LBC = 2 - 1 = 1. 

Therefore, n*( i - LBR ) + (j - LBC) = 6*2 + 1 = 13.

0
source

Source: https://habr.com/ru/post/956302/


All Articles