The best way to answer this is to use C examples. In C, there are two ways of keeping track of the length of an array:
- You store a variable telling you how long you made the array.
- You do what strings do and have the last element as 0. Then, you can implement a "string" length function that loops over the array until it finds zero.
For the first example, depending on what assembler you're using, you might be able to use some tricks. For example, in nasm you can do this:
SECTION .data
msg: db "Hello World",10,0 ; the 0-terminated string.
len: equ $-msg ; "$" means current address.
As you can see, we use the equ
operator to get nasm to calculate the difference between the current address and the start of msg
which should equal its length. Alternatively, you could just write the length in there as a digit.
For the second case, you could easily write a small function to do it. Roughly speaking, if you:
SECTION .text
global _mystrlen
_mystrlen:
push ebp ; conform to C calling conventions.
mov ebp, esp
xor eax, eax
lea ecx, [esp+8] ; load the start of the array into ecx
jecxz end ; jump if [ecx] is zero.
loop:
add eax, 1 ; could use inc eax as well.
add ecx, 4 ; always increment by (sizeof(int)). Change as appropriate
mov edx, [ecx] ; load ecx
cmp edx, 0 ; compare with zerp
je end ; if ecx is zero, we're done.
jmp loop ; if ecx isn't zero, loop until it is.
end:
leave ; restore stack frame
ret ; return. eax is retval
Note that I haven't tested that. It's just to give you an idea.
Edit I've tested the x86_64
version on Linux, using rdi
as param1, passing in int arr[10] = {1,2,3,4,5,6,7,8,9,0};
. Returns 9
as expected. Note that on Linux the underscore preceding mystrlen
is unnecessary.