问题
My program is supposed to do the following: -Getting continiously an integer from the user (x), -printing the character at the x position in the string. -The program exits when the user inputs 0.
.text
.globl __start
__start:
li $s3,20 #string length
start: li $v0,5
syscall
move $s0,$a0 #integer now in $a0
beq $s0,$zero,exit
li $s1,0 #counter is 0
la $s2,str #address of string now is $s2
loop:lbu $t1,0($s2) #choosing char of string
addi $s1,1 #increment counter by 1
addi $s2,1 #next char
beq $s1,$s0,print #is the char at the position we entered?
j loop
print: lbu $a0,0($t1) #<------------#
li $v0,11
syscall
j start
exit: li $v0,10
syscall
.data
str: .asciiz "abcdefghijklmnopqrst"
I keep getting: "Exception occured at PC=0x00400034" and "Bad address in data stack read: 0x..." exactly when i try to run the line i marked.
回答1:
$t1
does not contain a valid address at the point where you do lbu $a0,0($t1)
. What you've got in $t1
there is the last character read from the string before you exited your loop
loop.
I really don't see what the point of the loop is. You say that you have a string and and integer X, and you want to print the character at offset X in the string. So just read that character and you're done:
la $a1,string
addu $a1,$a1,$s0 # $a1 = &str[x]. assumes x is in $s0
lbu $a0,($a1) # read the character
li $v0,11
syscall # and print it
回答2:
.data
String: .space 1000
StringSize: .word 250
Msg: .asciiz "String length is: "
.text
.globl main
main:
lw $a1, StringSize
la $a0, String # a0 points to the string
li $v0, 8
syscall
add $t2, $a0, $zero # t2 points to the string
add $t1, $zero, $zero # t1 holds the count
addi $t3, $zero, 10
LoopString: lb $t0, 0($t2) # get a byte from string
beq $t0, $zero, EndLoopString # zero means end of string
beq $t0, $t3, Pointer # remove newline (linefeed)
addi $t1,$t1, 1 # increment count
Pointer: addi $t2,$t2, 1 # move pointer one character
j LoopString # go round the loop again
EndLoopString:
la $a0, Msg # system call to print
add, $v0, $zero, 4 # out a message
syscall
add $a0, $t1, $zero # system call to print
add, $v0, $zero, 1 # out the length worked out
syscall
add, $v0, $zero, 10
syscall # good byeee :) ...
来源:https://stackoverflow.com/questions/32819645/printing-the-x-char-in-a-string-mips