【问题标题】:Calculate length of array inside procedure using offset passed through parameter, Assembly language x8086使用通过参数传递的偏移量计算程序内部数组的长度,汇编语言 x8086
【发布时间】:2023-01-31 02:21:02
【问题描述】:

所以我试图通过使用参数中的偏移量来获取数组的长度,但它只返回 lenthof 偏移量。有什么办法可以做到这一点? `

INCLUDE Irvine32.inc
multiply proto,arr:ptr dword
.data
array dword 1,2,3,4,5,6,7,8,9,10
num dword 3
.code
main PROC
    invoke multiply,addr array
    exit
main ENDP

multiply proc,arr:ptr dword
    mov ecx,lengthof arr
    mov eax, ecx
    call writedec


    ret
multiply endp

END main

`

【问题讨论】:

  • 不,指针没有与之关联的数组大小。单独传递大小或使用终止符或长度前缀。
  • lengthof arr 就像 C 中的 sizeof 运算符;它是一个编译时常量,您不必在上面使用 #define。您不能像尝试在那里那样动态地使用它。

标签: assembly offset x86-16 procedure masm


【解决方案1】:

mulitply proc 不起作用的原因是 lengthof 严格来说是一个编译时常量。下面的代码非常好:

INCLUDE Irvine32.inc
multiply proto,arr:ptr dword
.data
array dword 1,2,3,4,5,6,7,8,9,10
num dword 3
.code
main PROC
    mov ecx,lengthof array ;assembler replaces this with 40 (byte count of your array)
    mov eax, ecx
    call writedec
    exit
main ENDP
END main

但是,如果您有一个函数试图像您所做的那样使用变量,那么这将不起作用。没有办法告诉 NASM 在这个函数中你的输入是一个双字数组,而不仅仅是一个双字。这是因为 CPU 在运行时没有这些信息。指针实际上并不携带任何关于它所指向的类型的信息。

multiply proc,arr:ptr dword
    mov ecx,lengthof arr  ;this just returns a constant value regardless of input.
    mov eax, ecx
    call writedec


    ret
multiply endp

为了做你想做的事,你需要将数组的长度作为一个额外的参数传递。我并不完全熟悉 proc 的 NASM 语法,但我认为您可以弄明白。如果你这样做:

invoke multiply, addr array, lengthof array

并相应地写下你的proc,你应该会得到想要的结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多