访问字符串中的一个字符
我正在使用诸如 SPIMS 或 MARS 之类的系统调用函数。
我正在读取一个字符串(它可以工作,因为我可以将其打印出来),如下所示:
li $v0, 8
la $a0, string
li $a1, 256
syscall
但是,我在访问字符串的单个字符时遇到问题。因此,如果我想访问第一个字符并打印它,我会尝试这样做:
la $t0, string
lb $a0, ($t0)
li $v0, 4
sys call
如果我尝试这样的操作:
la $a0, string
li $v0, 4
syscall
这会打印出整个字符串,因为字符串指向整个字符串。
如果我尝试类似的操作:
la $a0, string
lb $a0, ($t0)
li $v0, 4
syscall
它会给我一个越界错误。我不明白为什么 - 字符不是一个字节长,而这只是将字符串中的第一个字节加载到 $a0 中?
谢谢
I am using something like SPIMS or MARS with syscall functions.
I am reading in a string (and it works because I can print it out) as follows:
li $v0, 8
la $a0, string
li $a1, 256
syscall
However, I am having a problem accessing a single character of the string. So if I want to access the first character and print it, I am trying this:
la $t0, string
lb $a0, ($t0)
li $v0, 4
sys call
If I try something like this:
la $a0, string
li $v0, 4
syscall
This prints out the whole string as string points to the whole string.
If I try something like:
la $a0, string
lb $a0, ($t0)
li $v0, 4
syscall
It gives me an out of bound error. I don't understand why though - isn't a character a byte long and this just loads the first byte from the string into $a0?
Thank you
查看 MARS 系统调用函数的文档,您可以看到服务 4您正在使用的 $a0 预计是“要打印的以 null 结尾的字符串的地址”,这解释了您所看到的行为。
你想要的是函数11“打印字符”,它将低位字节打印为字符。换句话说,以下内容应该有效(未经测试):
Looking at the documentation for the MARS syscall functions you can see that service 4, which you're using, expects
$a0
to be "[the] address of null-terminated string to print", which explains the behavior you're seeing.What you want is function 11 "print character", which prints the low-order byte as a character. In other words the following should work (not tested):