我有以下需要转换为MIPS的C代码:
#include <stdio.h>
int main()
{
// Two strings, 100 bytes allocated for each
char s1[100];
char s2[100];
printf("Enter string 1: ");
scanf("%s", s1);
printf("Enter string 2: ");
scanf("%s", s2);
int index = 0;
while (1)
{
// Load characters from s1 and s2
char c1 = s1[index];
char c2 = s2[index];
// Current character is greater for s1
if (c1 > c2)
{
printf("s1 > s2\n");
break;
}
// Current character is greater for s2
if (c1 < c2)
{
printf("s1 < s2\n");
break;
}
// End of strings reached
if (c1 == 0)
{
printf("The strings are equal\n");
break;
}
// Compare next character
index++;
}
}
这是我到目前为止所拥有的:
.data
s1: .space 100
s2: .space 100
enters1: .asciiz "Enter string 1: "
enters2: .asciiz "\nEnter string 2: "
equalprint: .asciiz "The strings are equal\n"
s2lessthans1: .asciiz "\ns1 > s2\n"
s1lessthans2: .asciiz "\ns1 < s2\n"
.text
.globl main
main:
li $v0,4
la $a0,enters1
syscall
li $v0,8
la $a0,s1
addi $a1,$zero,20
syscall
li $v0,4
la $a0,enters2
syscall
li $v0,8
la $a0,s2
addi $a1,$zero,20
syscall
la $a0,s1
la $a1,s2
jal compare
beq $v0, $0, equalprint
slt $t0, $v0, $0
bne $t0, $0, str1smallerprint
j str2smallerprint
end:
addi $v0, $0, 10
syscall
compare:
add $t1, $s0, $t0
lbu $t2, 0($t1)
add $t1, $s1, $t0
lbu $t3, 0($t1)
slt $t4, $t2, $t3
bne $t4, $0, str1smaller
beq $t2, $0, equal
addi $a0, $t2, 0
li $v0, 11
syscall
addi $t0, $t0, 1
j compare
str1smaller:
addi $v0, $0, -1
jr $ra
str2smaller:
addi $v0, $0, 1
jr $ra
equal:
addi $v0, $0, 0
jr $ra
equalstrings:
la $a0, equalprint
li $v0, 4
syscall
j end
str1smallerprint:
la $a0, s1lessthans2
li $v0, 4
syscall
j end
str2smallerprint:
la $a0, s2lessthans1
li $v0, 4
syscall
j end
当我在MARS MIPS上组装并运行时,它表示成功组装,但是第16行
lbu $t2, 0($t1)
有错误:
Error in line 47: Runtime exception at 0x00400078: address out of range 0x00000000
我不确定我哪里出错或要解决什么问题以摆脱这个错误,有什么帮助吗?
编辑:固定代码
.data
s1: .space 100
s2: .space 100
enters1: .asciiz "Enter string 1: "
enters2: .asciiz "\nEnter string 2: "
equalprint: .asciiz "The strings are equal\n"
s2lessthans1: .asciiz "\ns1 > s2\n"
s1lessthans2: .asciiz "\ns1 < s2\n"
.text
.globl main
main:
li $v0, 4
la $a0, enters1
syscall
li $v0, 8
la $a0, s1
addi $a1, $0, 100
syscall
li $v0, 4
la $a0, enters2
syscall
li $v0, 8
la $a0, s2
addi $a1, $0, 100
syscall
loop:
lb $t1,s1($t0)
lb $t2,s2($t0)
blt $t1,$t2,s2lts1
bgt $t1,$t2,s1lts2
beq $t1,$0,s1eqs2
addi $t0,$t0,1
j loop
s1lts2:
li $v0, 4
la $a0, s1lessthans2
syscall
j end
s2lts1:
li $v0, 4
la $a0, s2lessthans1
syscall
j end
s1eqs2:
li $v0, 4
la $a0, equalprint
syscall
end:
li $v0, 10
syscall
答案 0 :(得分:1)
如果你追踪代码,那么当你点击lbu
时,t0
和s0
都没有被初始化,如果MARS将你的寄存器初始化为0,那么,是的,你的t1
将结束NULL指针。