title: Convert C to MIPS - Nested Arrays
body: <p>I am studying the MIPS assembly language and came across this example in the book and to me it seems incorrect. If it is it wouldn't be the first mistake I found in this book.</p>
  
  <p>The variables <code>f</code> and <code>g</code> are assigned registers <code>$s0</code> and <code>$s1</code> respectively, the base addresses for the arrays <code>A</code> and <code>B</code> are <code>$s6</code> and <code>$s7</code> respectively.</p>
  
  <p>The c code example is:</p>
  
  <pre><code>f = g - A[B[4]];
  </code></pre>
  
  <p>And the corresponding MIPS assembly provided is:</p>
  
  <pre><code>lw  $t0, 16($s7)
  lw  $s0, 0($t0)
  sub $s0, $s1, $s0
  </code></pre>
  
  <p>From my understanding the above MIPS code would load some random data from memory at the address provided by <code>$t0</code> and then subtract it from <code>$s1</code> and not access the index <code>$t0</code> of the array denoted in <code>$s6</code>.</p>
  
  <p>The correct MIPS assembly from my understanding would be along the lines of:</p>
  
  <pre><code>lw  $t0, 4($s7)
  add $t0, $t0, $s6
  sll $t0, $t0, 2
  lw  $s0, 0($t0)
  sub $s0, $s1, $s0
  </code></pre>
  
  <p>I am correct that this is an error in the book or am I misunderstanding something.</p>
  
  <hr>
  
  <p>Edit: Fixed an error in the corrected mips code as pointed out by Chris Dodd</p>