问题
I have allocated a certain amount of memory and would like to assign the location of this memory to variable I have declared in the .data section of the program. I know how to assign the memory location to the variable, but once I do that how can I use that variable to access the allocated memory?
回答1:
MIPS has many instructions for loading and storing to memory: load word (lw), load halfword (lh), load byte(lb), store word (sw), store half word (sh), and store byte (sb) just to name a few. They all use the same sort of syntax so here is an example from loading from a memory location:
lw $t, C($s)
which will load the word from the memory location held in register $s plus C to register $t. ie $t = [$s + C]
Similarly for storing:
sw $t, C($s)
which will store the word in register $t to the memory location in $s plus C. ie [$s + C] = $t
回答2:
If I understand your problem correctly, you will want to use the la (load address) instruction to get the address into a register. You will then use the lw (load word) and sw (store word) instructions to manipulate the data. For instance, consider the following piece of code
.data
tmpval: .word 5
__start:
sub $sp, $sp, 12
sw $ra, 0($sp) # Return addy
sw $t0, 4($sp)
sw $t1, 8($sp)
la $t0, tmpval
lw $t1, 0($t0) # $t1 == tmpval == 5
li $t1, $2 # $t1 == 2
sw $t1, 0($t0) # tmpval == 2
lw $ra, 0($sp)
lw $t0, 4($sp)
lw $t1, 8($sp)
add $sp, $sp, 12
jr $ra
So in the inner-block of code you can see that you treat $t0 (or any other register for that matter) as a memory location and work with it appropriately.
来源:https://stackoverflow.com/questions/10324691/storing-addresses-in-a-register-for-mips