B Basak - 9 months ago 30

C Question

There is an array **a[3][4]** and we have to find the address of **a[2][2]** using **row major order** and **1001 as base address**. I found 2 formulas do find the address:

`For any array a[M][N] Row Major Order:`

1) a[i][j] = Base Address+Datatype Size[(N*i)+j]

2) a[i][j] = Base Address+Datatype Size[N*(i-1)+(j-1)]

I tried both the formulas but the first one yielded the correct result but not the second one. Here is how I found the address of a[2][2] using row major order:

`Using Formula 1:`

a[2][2] = 1001+2[(4*2)+2]

= 1001+2[10]

= 1001+20

= 1021 (correct answer)

Using Formula 2:

a[2][2] = 1001+2[4*(2-1)+(2-1)]

= 1001+2[4+1]

= 1001+2[5]

= 1001+10

= 1011 (Wrong Answer)

Is there any error in my 2nd formula or have I done something wrong in the calculation using 2nd formula? Why aren't both the answers coming same?

Answer

as amit said, the equations are different, so they are not going to give the same result. when ever in doubt about a problem like this, try putting some numbers in the equations and try them out, so if we are trying for an array of size 4, at position 2,2

equation 1: (N * i) + j, (4 * 2) + 2 = 10

equation 2: N * (I - 1) + (j - 1) = 9

as you can see as they are not the same result, the problem is not in your code, but in the equation itself

if you are feeling brave, you can also try and prove it by induction as well

To find the memory address number, you will also need to know how much space an integer is occupying in memory as well. You can do this with `sizeof(int);`

which will output how many bytes the integer is using on the system.

you will also need to know how an array of arrays is formatted in memory. Just like a normal array, and array of arrays is contiguous, meaning that there are no gaps in memory between the array elements. So an array a[2][2] {1,2}, {3,4} would be formatted like this. 1, 2, 3, 4.

using this you should be able to find the memory location with the following equation `address location of array a[I][j] = B + W * [N * (I- Lr) + (J - Lc)]`

where:
B is the base address
I is the row subscript of the element you are looking for
J is the column element you are looking for
W is the size of an element
Lr is the lower limit of a row - 0 if not given
Lc is the lower limit of a column - 0 if not given
M is the number of rows of the matrix
N is the number of columns of the matrix

Source (Stackoverflow)