MIPS汇编语言中可变长度的数组

时间:2022-01-15 19:39:01

In MIPS, I know that I can declare an array as:

在MIPS中,我知道可以将数组声明为:

list: .space 20

However, what if I wanted to create an array of different size based on user input? Is this possible?

但是,如果我想根据用户输入创建一个不同大小的数组,该怎么办?这是可能的吗?

For example, the program would ask the user to input an integer N and create an array of length N.

例如,程序将要求用户输入一个整数N并创建一个长度为N的数组。

2 个解决方案

#1


2  

That's a good question. In assembly language, variables declared as you've done are statically allocated, that is they're allocated at assembly time. If you want to allocate a variable based on user input at run time you have at least two choices: Allocate space on the stack (and watch for stack overflow) or allocate from a memory pool, usually called the heap. In either case, the allocation is done at rum time rather than at assembly time.

这是一个很好的问题。在汇编语言中,像您所做的那样声明的变量是静态分配的,即它们是在汇编时分配的。如果您希望在运行时基于用户输入分配变量,您至少有两个选择:在堆栈上分配空间(并注意堆栈溢出)或从内存池中分配(通常称为堆)。在任何一种情况下,分配都是在朗姆时间完成的,而不是在组装时间。

#2


2  

You can use system call 9 to allocate memory on the heap

您可以使用system call 9在堆上分配内存

li $a0, numbytes
li $v0, 9
syscall

The address is returned in $v0

地址以$v0返回

#1


2  

That's a good question. In assembly language, variables declared as you've done are statically allocated, that is they're allocated at assembly time. If you want to allocate a variable based on user input at run time you have at least two choices: Allocate space on the stack (and watch for stack overflow) or allocate from a memory pool, usually called the heap. In either case, the allocation is done at rum time rather than at assembly time.

这是一个很好的问题。在汇编语言中,像您所做的那样声明的变量是静态分配的,即它们是在汇编时分配的。如果您希望在运行时基于用户输入分配变量,您至少有两个选择:在堆栈上分配空间(并注意堆栈溢出)或从内存池中分配(通常称为堆)。在任何一种情况下,分配都是在朗姆时间完成的,而不是在组装时间。

#2


2  

You can use system call 9 to allocate memory on the heap

您可以使用system call 9在堆上分配内存

li $a0, numbytes
li $v0, 9
syscall

The address is returned in $v0

地址以$v0返回