这几乎可以肯定是因为您的字符数组不足以容纳您正在阅读的所有数据。具体来说,字符串"zero"
(带有\0
终止符)需要五个字节,而不是四个。超出数组末尾的写入是未定义的行为,一旦这样做,所有行为保证都将消失。
例如,当您声明:
char rd[4];
char rs[4];
char rt[4];
你可能会像这样布置内存:
rt: [1] [2] [3] rs: [1] [2] [3] rd: [1] [2] [3]
+---+---+---+---+---+---+---+---+---+---+---+---+
| | | | | | | | | | | | |
+---+---+---+---+---+---+---+---+---+---+---+---+
并执行命令:
sscanf ("or $a0, $t4, $zero", "or $%[^,], $%[^,], $%s", rd, rs, rt);
可能会导致按所示顺序填充内存块,从而导致以下内存写入,其中.
表示\0
:
rt: [1] [2] [3] rd: [1] [2] [3] rs: [1] [2] [3]
+---+---+---+---+---+---+---+---+---+---+---+---+
| | | | | a | 0 | . | | | | | |
+---+---+---+---+---+---+---+---+---+---+---+---+
+---+---+---+---+---+---+---+---+---+---+---+---+
| | | | | | | | | t | 4 | . | |
+---+---+---+---+---+---+---+---+---+---+---+---+
+---+---+---+---+---+---+---+---+---+---+---+---+
| z | e | r | o | . | | | | | | | |
+---+---+---+---+---+---+---+---+---+---+---+---+
导致最终情况:
rt: [1] [2] [3] rd: [1] [2] [3] rs: [1] [2] [3]
+---+---+---+---+---+---+---+---+---+---+---+---+
| z | e | r | o | . | 0 | . | | t | 4 | . | |
+---+---+---+---+---+---+---+---+---+---+---+---+
您可以在那里看到rd
by的覆盖rt
使它看起来像没有被读入rd
。
现在请注意may
上面这个词的使用,不能保证内存会以这种方式布局,这只是您的结果发生原因的一种可能解释。
最重要的是,您不应该将更多的数据读入数组中。
至于如何解决这个问题,在 C 语言中有许多可靠的获取输入的方法,例如这个。