0
我想計算一個用戶給出的字符串的長度。每次我嘗試運行代碼時,都會收到消息「PC發生異常=(某個地址),然後是消息:」數據/堆棧中的地址錯誤讀取:(另一個地址)。我知道它與堆棧有關,但我無法弄清楚問題所在。 MIPS中的代碼是bello,我正在使用QtSpim。您的幫助將非常感激。嘗試顯示用戶給定的字符串長度時遇到異常。 MIPS
sentence: .space 6
Prompt: .asciiz "Enter the sentence. Max 6 characters, plus a terminator .\n"
.text # Start of code section
main: # The prompt is displayed.
li $v0, 4 # system call code for printing string = 4
la $a0, Prompt # load address of string to be printed into $a0
syscall # call operating system to perform operation;
# $v0 specifies the system function called;
# syscall takes $v0 (and opt arguments)
##read the string, plus a terminator, into the sentence
la $t0, sentence
li $t0, 6
li $v0, 8
add $v0, $zero, $zero #initialize length to zero
loop:
lbu $s0, 0($t0) #load one character of string
addi $t0,$t0,1 #point to next character
addi $v0,$v0,1 #increment length by 1
bne $s0,$zero, loop #repeat if not null yet
end_loop:
addi $v0, $v0, -1 #don't count the null terminator
li $v0, 4 #display the actual length
syscall
exit: #exit the program
li $v0, 10
syscall
當我試圖搭乘:li $ t0,6時,它顯示提示兩次。但是當我保留那條線時,提示只顯示一次。但是,在嘗試刪除兩條線時,我仍然沒有預期的結果。 – T4000 2013-04-25 10:34:40
@ T4000:這是可以預料的,因爲你再次執行系統調用4(print_string)來結束你的代碼,並且仍然有'$ a0'指向'提示符'。你也沒有實際讀取用戶字符串的代碼。 – Michael 2013-04-25 11:18:55