Search code examples
arraysmemory-managementmipsmars-simulator

How to allocate an array of variable size in MIPS?


I am trying to learn MIPS. Problem I encountered is that I can't create array of variable size. For instance in Java you can do

int n = 3;
int [] arr = new int[n];

I'm trying to do the same thing in MIPS with something like:

.text 
.global main

main:
li $t1, 4

.data
arr: .space $t1

But this gives an error:

".space" requires a non-negative integer

Any suggestions? How can I solve this.


Solution

  • Referencing this question, one solution would be to allocate space on the heap for your array. Assuming you're using MARS to run your MIPS code, you can load 9 into $v0 and $a0 should represent the number of bytes of memory to allocate. You should then perform a syscall.

    The address of the allocated memory is then returned in $v0.