Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2D array calculation formula

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

I am just trying to calculate a simple point in a 2D and just wanted to double check that I plugged in the right 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 correctly here? I wasn't sure if i plugged in the right values?

like image 1000
user1789951 Avatar asked Oct 19 '13 05:10

user1789951


1 Answers

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

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 row just follows the previous one in memory.

The address in of an element at (row, col) is

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

In your case you know that the element you are searching is 30 rows lower and 40 elements to the right of given element, therefore the address will be

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

totaling to 88640.

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

like image 163
6502 Avatar answered Oct 28 '22 01:10

6502