[英]Calculate length of array inside procedure using offset passed through parameter, Assembly language x8086
So i am trying to get the length of array by using the offset in the parameter but it is only returning lenthof offset.所以我试图通过使用参数中的偏移量来获取数组的长度,但它只返回 lenthof 偏移量。 Is there any way I can do this?
有什么办法可以做到这一点? `
`
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
` `
Most assemblers allow you to do compile-time "label arithmetic" (as I like to call it) where you can subtract one label from another to get the distance between them measured in bytes.大多数汇编程序都允许您进行编译时“标签算术”(我喜欢这样称呼它),您可以从一个标签中减去另一个标签以获得它们之间的距离(以字节为单位)。 The syntax may vary depending on the assembler but usually it will look something like this:
语法可能因汇编程序而异,但通常看起来像这样:
array dword 1,2,3,4,5,6,7,8,9,10
arrayEnd label byte ;this exists just to mark the end
mov ecx, offset (arrayEnd-array) ;should equal 40 since each entry is 4 bytes.
mov eax,ecx
call writedec
If you use this technique, the distance is always measured in bytes.如果您使用此技术,则距离始终以字节为单位进行测量。 Unlike C, assembly does not auto-scale pointer arithmetic by the size of the data type you're working with.
与 C 不同,汇编不会根据您正在使用的数据类型的大小自动缩放指针算法。 Keep this in mind when indexing the array, or you'll be loading the wrong values.
在索引数组时请记住这一点,否则您将加载错误的值。
There are limitations to this method, however.但是,此方法有局限性。 For one it doesn't work with
malloc
or any runtime memory allocation like that.首先,它不适用于
malloc
或任何类似的运行时内存分配。 This method is purely a compile-time constant, it's the equivalent of just counting them yourself (in your head) and writing that constant in your code as a "magic number."此方法纯粹是一个编译时常量,相当于您自己(在脑海中)计算它们并将该常量作为“幻数”写入您的代码。
Also, it can't tell the difference between "empty slots" in your array.此外,它无法区分数组中的“空槽”。 For example:
例如:
array dword 1,2,3,4,5,0,0,0,0,0
arrayEnd label byte
Let's say you intended the last five zeroes as "free space" for more data, and when you measure the size you only want to count data that isn't "free space."假设您打算将最后五个零作为更多数据的“可用空间”,而当您测量大小时,您只想计算不是“可用空间”的数据。 The
arrayEnd-array
method won't help you with that. arrayEnd-array
方法不会帮助你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.