title: Nested Arrays in Assembly, reach desired index
body: <p>This is about reaching desired index in nested arrays in Assembly language. Let me start.</p>
  <ul>
  <li>First of all, I know that for a given array &quot;A&quot;, you can reach A[i][j] by; <em>A + i * (C * K) + j * K</em> given that C is the element number in an array. K is the byte that type of the elements in A requires.</li>
  </ul>
  <p>So it makes sense. For example, you want to reach int A[3][4] in A[5][5], you have to get through 3 arrays in A. Each of them consists 4 elements that costs 4 bytes per element. Therefore;
  <em>A + 3 ( 4 * 5 ) + 4 * 4</em>. First, you get through 12 elements which you should walk on the addresses by 48 bytes. Then, you are at the beginning of the desired row. Then you skip 4 elements (16 bytes) and desired column, in other words 5th element in that row.</p>
  <p>However, we had an example in class and I totally do not understand what is going on. I can not mail teacher since I know that will not result in any. So please help me to understand this.</p>
  <pre><code>#define M ??
  #define N ??
  long P[M][N];
  long Q[N][M];
  long sum_elem(long i, long j)
  {
  return P[i][j] + Q[j][i];
  }
  </code></pre>
  <pre><code># long sum_elem(long i, long j)
  # in %rdi, j in %rsi
  1 sum_element:
  2 leaq 0(,%rdi,8), %rdx          # Computing 8*i and copy it onto %rdx.
  3 subq %rdi, %rdx                # 8*i - i = 7*i
  4 addq %rsi, %rdx                # 7*i + j 
  5 leaq (%rsi,%rsi,4), %rax       # 4*j + j = 5*j
  6 addq %rax, %rdi                # 5*j + i 
  7 movq Q(,%rdi,8), %rax          # Retrieve [Q + 8*(5*j + i)]. 
  8 add P(,%rdx,8), %rax           # Retrieve [P + 8*(7*i + j)] and add it to %rax.
  9 ret
  </code></pre>
  <p>As you can guess, we are expected to answer for M and N values. It is stated that M = 5 and N = 7 however, if we investigated one of the above, i.e. [P + 8*(7*i + j)], then 8 stands for K value in our very beginning definition. 7 stands for C, which is the number of elements that an array in A contains. Therefore, I believe that it should be M = 7 and N = 5 which is the reverse of the answer.</p>
  <p>Am I correct and it is just an typo or do I miss something?</p>
  <p>Thank you all.</p>
  <p>EDIT: I had a typo while writing, thanks to the answer it is corrected.</p>