Electrical – Clarification on MIPS sw and lw


If I have the following code in C

A[1] = 2;

Where the starting address A[0] is $s0.

addi $t0, $s0, 1 #t0->A[0]
lw $t1, 0($t0) #t1->A[1]
addi $t1, $t1, 2

This is where I am a bit confused. Is it necessary to add:

sw $t1, 0($t1)

Or is the code fine as is? I think it is fine because, I am adding 2 to the contents of $t1, which is effectively, A[1] = 2.

Best Answer

If &A is stored in $s0, then A[1] = 2 compiles to

ori $t0, $0, 2      # Move 2 into $t0
sw $t0, 4($s0)      # Store $t0 into $s0 + 4 (because ints are 4 bytes)

As mentioned in the comments, your code doesn't make a lot of sense because you seem to be doing something resembling x = A[1] +2. You have to use a sw because the C code stores a value to the array.