Array Memory Calculation
1 D Array address of an element
Address of A[I] = B + W*(I-LB)
I = address of the element to be found
B = Base address(first address or address of the first element)
W = Size of the data type
LB = Lower Limit/Lower Bound(Starting index)
UB = Upper Limit/Upper Bound(last index)
int A[] = {7,8,9,10,5};
Example:
Given the base address of an array A[2100 ....2500] as 1020 and the size of each element is 2 bytes in the memory. Find the address of A[2300].
Answer:
B = 1020
LB = 2100
W = 2
I = 2300
Address of A[2300] = 1020 + 2*(2300-2100)
= 1020 + 2*200
= 1420
2D Array
Suppose
2 8 3 4
1 2 3 4
2 2 2 2
3 3 3 3
--Express
-Row Major
{{2,8,3,4},{1,2,3,4},{2,2,2,2},{3,3,3,3}}
-Column Major
{{2,1,2,3},{8,2,2,3},{3,3,2,3},{4,4,2,3}}
Row Major
Address of A[I][J] = B + W * ((I – LR) * N + (J – LC))
I = Row Subset of an element whose address to be found,
J = Column Subset of an element whose address to be found,
B = Base address,
W = Storage size of one element store in an array(in byte),
LR = Lower Limit of row/start row index of the matrix(If not given assume it as zero),
LC = Lower Limit of column/start column index of the matrix(If not given assume it as zero),
Number of column given in the matrix N = Upper Bound of column – Lower Bound of column + 1
Example:
Given an array, arr[1………10][1………15] with base value 100 and the size of each element is 1 Byte in memory. Find the address of arr[8][6] with the help of row-major order.
Answer:
B (Base address) = 100
W (size) = 1
To find I = 8 (row) , J = 6 (column)
LR = 1 (lower bound of row)
LC = 1 (lower bound of column)
UR = 10 (upper bound of row)
UC = 15 (upper bound of column)
N(no of columns) = UC - LC + 1 = 15 - 1 + 1 =15
Address of A[I][J] = B + W * ((I – LR) * N + (J – LC))
A[8][6] = 100 + 1*((8-1)*15+(6-1))
= 100 + 1*(7*15 + 5 )
= 100 + (105+5)
= 100 + 110
= 210
Column Major
Address of A[I][J] = B + W * ((J – LC) * M + (I – LR))
I = Row Subset of an element whose address to be found,
J = Column Subset of an element whose address to be found,
B = Base address,
W = Storage size of one element store in any array(in byte),
LR = Lower Limit of row/start row index of matrix(If not given assume it as zero),
LC = Lower Limit of column/start column index of matrix(If not given assume it as zero),
UR = Upper Limit of row/start row index of matrix,
UC = Upper Limit of column/start column index of matrix
M = Number of rows given in the matrix.
M = UR-LR+1
Given an array arr[1………10][1………15] with a base value of 100 and the size of each element is 1 Byte in memory find the address of arr[8][6] with the help of column-major order.
LR=1
LC=1
UR=10
UC=15
I=8
J=6
B=100
W=1
M = UR - LR + 1 = 10 - 1 + 1 = 10
Address of A[I][J]=B+W((J-LC)*M+(I-LR)
A[8][6]=100+1*((6-1)*10+(8-1))
=100+57
=157