要转换为mips汇编语言的C ++程序
#include <iostream>
using namespace std;
int main() {
int a = 1;
int b = 1;
int array[a];
while ( a < 10)
{
array[a] = b + a;
cout << array[a] << endl; // print elements in array //check values in array
a +=1;
}
system("pause");
return 0;
}
Mips汇编语言程序
.data
str: .ascii "abcdef"
array: .space 20
.text
main:
li $s0, 1 # a = 1
li $s2, 1 # b = 1
loop:
la $t1, array
slti $t0, $s0, 3 # t0<- 1 if a < 3
beq $t0, $zero, exit
sll $t0, $s0, 2 # t1<- 4*a
add $t1, $t1, $t0 # new base addr
add $t2, $s2, $s0 # t2<- a+b
sw $t1, 0($t2) # D[a]=a+b
addi $s0, $s0, 1 # a = a +1
j loop # goes to loop: label
exit:
li $v0, 10 # v0<- (exit)
syscall
我已经尝试过lw,sw,lb,sb将寄存器$ t2的值放入数组中,但是当我在Mars编译器中单步运行程序时,我仍然会出现错误
更新了Mips汇编语言程序
.data
str: .ascii "abcdef"
.align 2
array: .space 40
.text
main:
li $s0, 1 # a = 1
li $s2, 1 # b = 1
loop:
la $t1, array
slti $t0, $s0, 3 # t0<- 1 if a < 3
beq $t0, $zero, exit
sll $t0, $s0, 2 # t1<- 4*a
addu $t2, $t1, $t0 # new base addr
add $s1, $s0, $s2 # s1<- a+b
sw $s1, 0($t2) # D[a]=a+b
li $v0, 1 # load appropriate system call code into register $v0;
# code for printing integer is 1
lw $a0, 0($t0)
addiu $t0, $t0, 4
syscall # call operating system to perform print operation
addi $s0, $s0, 1 # a = a +1
j loop # goes to loop: label
exit:
li $v0, 10 # v0<- (exit)
syscall
我运行此程序并收到此错误:“地址超出范围0x00000004” 我想打印我的数组的值来检查它是否正确。
答案 0 :(得分:2)
您的代码中存在多个错误。 关于在数组中存储项目,您必须使用索引(乘以4)添加数组的基址以获取要存储的项目的地址。
假设$s0
持有a而$s2
持有b,要存储D[a] = a + b
,您会:
la $t1, array
sll $t0, $s0, 2
addu $t2, $t1, $t0 # $t2 is &D[a]
add $s1, $s0, $s2 # $s1 = a + b
sw $s1, 0($t2) # D[A] = a + b
请注意,你没有保留足够的内存来容纳数组D中的10个项目,假设int是32位宽,那么每个项目的长度是4个字节,因此你应该保留40个字节......
您还应该确保数组在字边界处正确对齐。为此,您可以指示汇编程序使用.align 2
指令为您进行对齐,例如:
.align 2
array: .space 40
答案 1 :(得分:0)
intN;
cout<<"Enter the array size: ";
cin>>N; //size must be less than MAX_SIZE
int one[MAX_SIZE];
int two[MAX_SIZE];
cout<<"Ente the elements of array one:"<<endl;
for(inti = 0; i<N;i++)
cin>>one[i];
cout<<"Ente the elements of array two:"<<endl;
for(inti = 0; i<N;i++)
cin>>two[i];
int result = compare(one,two,N);
if(result == 0)
cout<<"Array one is Equal to array two"<<endl;
elseif(result==-1)
cout<<"Array one is less than array two"<<endl;
elseif(result==1)
cout<<"Array one is greater than array two"<<endl;