# Why is my assembly code in MIPS wrong?

I've started studying assembly, and I've been tryign to solve this problem:

For the following C statement, what is the corresponding MIPS assembly code? Assume that the variables f, g, h, i, and j are assigned to registers $s0,$s1, $s2,$s3, and $s4, respectively. Assume that the base address of the arrays A and B are in registers$s6 and $s7, respectively: B[8] = A[i−j]; So, I did this: sub$t0, $s3,$s4 // temp = i - j
sll $t0,$t0, 2   // temp = temp*2^2= 4*temp
add $t0,$t0, $s6 // temp = &A[i-j] lw$t1, 0($t0) // t1 = temp sw$t1, 32 ($s7) // B[8] = t1 = temp = A[i-j]  But looking at the book's solution manual to verify that my answer is correct, I got this: sub$t0, $s3,$s4
add $t0,$s6, $t0 lw$t1, 16($t0) sw$t1, 32($s7)  I am confused. How did they come up with the third statement lw$t1, 16($t0) ? • I'm not familiar with MIPS assembly language so I don't know if your code is correct, but there are usually many different ways to solve a single problem. One way is not necessarily better than the other way. Jun 4 '16 at 10:09 • Assume: Base address of A =28 And I-J = 3 so we want to access the 3rd element from the array A in this case the desired byte address will be 28+3*4 = 40 according to the book solution manual the accessed byte address will be 28 +3 + 16 = 47 this is not even a number divisible by 4 .So this answer seems wrong Jun 4 '16 at 10:26 • The book's answer also seems incorrect to me. Jun 4 '16 at 10:33 ## 2 Answers The books solution is wrong: sub$t0, $s3,$s4
add $t0,$s6, $t0 lw$t1, 16($t0) sw$t1, 32($s7)  The use of lw and sw instruction imply that the arrays A and B are 32 bit in size, otherwise instructions such as lb/lbu, lh/lhu would be used to load 8 or 16 bit wide entities (or LD, SD for 64 bit machines). However, the address calculation does not take the size of the elements into account. This causes the address calculation to be wrong. You did it right by scaling the offset into the array using the sll instruction. I am confused. How did they come up with the third statement lw$t1, 16(\$t0) ?

The offset of 16 makes no sense in this context. The offset of 32 in the store instruction is fine because it directly addresses element 8 in the B array as it should.

I have the same solution manual. It is not wrong, it is just answering question 2.4.1. The question you are asking about is Exercise 2.4, which is not included in the solution manual. What you did is correct.

• It is answering another question, so it is still wrong. Sep 18 '18 at 17:10