【问题标题】:Assembly x86 putting values into array with loop汇编 x86 将值放入带有循环的数组中
【发布时间】:2017-05-19 22:33:38
【问题描述】:

我想将数字放入长度为 10 的数组中,但每个数字都比最后一个数字大 1。 这意味着:myArray = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

我试过这个:

理想
模型小
堆叠 100h

数据段

intArray db 10 重复 (0)
索引分贝 1

代码段

开始:
mov 斧头,@DATA
mov ds, 斧头
循环数组:
mov al, [索引]
添加 [intArray+index], al ;这是问题
公司 [索引]
cmp [索引], 11
jb 循环数组
退出:
mov ax, 4c00h
整数 21 小时
结束开始

但是我无法将索引添加到[intArray + index],所以我尝试将它添加到[intArray+al],也不起作用。

如何每次都将索引添加到下一个数组的值?

【问题讨论】:

  • {add [intArray + al], al} 应该可以工作,为什么不呢?它编译了吗?
  • 为什么要添加索引到任何东西? MOV它在那里。你可能不得不使用BX 来索引:mov bl,[index] ; loopArray: mov [intArray + bx],bl ; inc bl : cmp bl,11 : jb loopArray 或类似的。
  • 现在我的循环看起来像这样:' loopArray: mov bl, [index] ; mov [intArray+bl], bl ;公司 [索引] ; cmp [索引], 11 ; jb loopArray ' 还是不行。
  • 是的,它确实可以编译。

标签: arrays loops assembly x86


【解决方案1】:

myArray = 0、1、2、3、4、5、6、7、8、9。

这些是您希望数组包含的数字。但是,由于您将 index 变量(您将用于索引和存储)初始化为 1(使用 index db 1),这将导致另一个结果。
只需设置索引:

index db 0

这样设置还有另一个原因! 在 [intArray+index] 符号中,index 部分是数组中的一个 offset。偏移量始终是基于零的数量。您编写程序的方式,它将在数组后面写入第 10 个值。

添加 [intArray+index], al ;问题来了

你说得对,这就是问题所在。一些汇编器不会编译它,而其他汇编器只会添加这两个变量的地址。都不适合你的目的。您需要将 index 变量的内容放入寄存器并使用该操作数组合。

    intArray db 10 dup (0)
    index    db 0
    ...
loopArray:
    movzx    bx, [index]
    mov      [intArray+bx], bl ;Give the BX-th array element the value BL
    inc      [index]
    cmp      [index], 10
    jb       loopArray

使用此代码,index 将从 0 开始,然后只要 index 小于 10,循环就会继续。


当然,你完全可以不使用 index 变量来编写这个程序。

    intArray db 10 dup (0)
    ...
    xor      bx, bx            ;This make the 'index' = 0
loopArray:
    mov      [intArray+bx], bl ;Give the BX-th array element the value BL
    inc      bx
    cmp      bx, 10
    jb       loopArray

鉴于数组最初用零填充,您可以替换:

    mov      [intArray+bx], bl ;Give the BX-th array element the value BL

与:

    add      [intArray+bx], bl ;Give the BX-th array element the value BL

请记住,这只有在数组预先填充零时才有效!

【讨论】:

  • 谢谢你,我昨天做了这个,这是正确的答案。
  • 很高兴为您提供帮助!
  • 你好@SepRoland。如何将小矩阵覆盖成大矩阵?
  • @SepRoland 如果数组是 intArray db 10 dup (3 dup(0)) 怎么办?
  • @FereydoonBarikzehy 这相当于intArray db 30 dup (0)。该数组将从 30 个零元素开始,代码将填充从 0 到 29 的数字。
猜你喜欢
  • 1970-01-01
  • 2018-07-07
  • 1970-01-01
  • 2011-10-11
  • 1970-01-01
  • 2017-01-23
  • 2013-07-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多