Thomas
Thomas

Reputation: 49

Converting C array accesses to MIPS

The question is:

Assume that the base address of the arrays A and B are in registers $s6 and $s7, respectively.

And the variables f and g are assigned to registers $s0, $s1, respectively.

What is the corresponding MIPS assembly code for the following C code: f = g - A[B[4]];

My idea is:

lw $t0, 16($s7) # $t0 = B[4]
lw $t1, 64($s6) # $t1 = A[B[4]]
sub $s0, $s1, $t1 # $s0 = $s1 - $t1

I got wrong on this answer and I don't know why. Can someone help me on an idea or explanation, please?

Upvotes: 2

Views: 290

Answers (1)

ggorlen
ggorlen

Reputation: 56855

Good attempt, but your code can't be right because $t0 was loaded but never used. I'm also not sure where the number 64 came from, but basically that should be the value pulled from B[4], $t0.

You might be confused by the nested array access A[B[4]]. Conceptually, this is using the value stored in B[4] as an index into A. It's better to expand that out and start with the single-operation-per-line C code:

t0 = B[4];
t1 = A[t0];
f = g - t1;

Now it's easier to come up with:

lw $t0, 16($s7)    # B_val = B[4]
sll $t0, $t0, 2    # B_val *= 4
addu $t2, $t0, $s6 # A_offset = B_val + A_base
lw $t1, ($t2)      # A_val = A[A_offset]
sub $s0, $s1, $t1  # f = g - A_val

Here, I assume the B value needs to be multiplied by 4.

You can always write a program to validate your work (at least, after the exam):

    .data
A: .word 1, 1, 1, 1, 24
B: .word 1, 1, 1, 1, 4

    .text
main:
    la $s6 A           # A_base
    la $s7 B           # B_base
    li $s1, 42         # g = 42

    lw $t0, 16($s7)    # B_val = B[4]
    sll $t0, $t0, 2    # B_val *= 4
    addu $t2, $t0, $s6 # A_offset = B_val + A_base
    lw $t1, ($t2)      # A_val = A[A_offset]
    sub $s0, $s1, $t1  # f = g - A_val

    li $v0, 1
    move $a0, $s0
    syscall            # => should be 42 - 24 = 18

    li $v0, 10
    syscall

Upvotes: 1

Related Questions