Problem Statement - 2-D Array Element Address Calculation
ARR[15][20] is a two-dimensional array, which is stored in the memory along the row with each of its elements occupying 4 bytes. Find the address of the element ARR[5][15], if the element ARR[10][5] is stored at the memory location 35000.
Solution
TC++ #5772
ROW MAJOR:
Loc(ARR[I][J]) =BaseAddress + W [( I – LBR)*C + (J – LBC)]
(where W=size of each element = 4 bytes, R=Number of
Rows=15, C=Number of Columns=20 )
Assuming LBR = LBC = 0
LOC(ARR[10][5])
35000 = BaseAddress + W(I*C + J)
35000 = BaseAddress + 4(10*20 + 5)
35000 = BaseAddress + 4(205)
35000 = BaseAddress + 820
BaseAddress = 35000 - 820
= 34180
LOC(ARR[5][15])= BaseAddress + W(I*C + J)
= 34180 + 4(5*20 + 15)
= 34180 + 4(100 + 15)
= 34180 + 4 x 115
= 34180 + 460
= 34640
OR
Loc(ARR[I][J]) = Ref. Address + W (( I – LR)*C + (J – LC))
(where
W=size of each element = 4 bytes,
R=Number of Rows =15, C=Number of Columns=20
Reference Address= Address of given cell ARR[10][5]=35000
LR = Row value of given cell = 10
LC = Column value of given cell = 5
LOC(ARR[5][15]) = LOC(ARR[10][5]) + 4((5-10)*20 + (15-5))
LOC(ARR[5][15]) = 35000 + 4(-100 + 10)
= 35000 + 4[-90]
= 35000 -360
= 34640