Array length: Difference between revisions

Content added Content deleted
Line 2,840: Line 2,840:
orange
orange
</pre>
</pre>


=={{header|Z80 Assembly}}==
Arrays don't have an "end" as defined by the language, so there are a couple ways to mark the end of an array. One is with a null terminator, and the other is with a pre-defined size byte stored at the beginning. Using a null terminator isn't the best choice for a general-purpose array since it means your array cannot contain that value anywhere except at the end. However, since having the size already determined defeats the purpose of this task, the null-terminator method will be used for this example.

The simplest way to implement an array of variable-length strings is to have the array contain pointers to said strings rather than the strings themselves. That way, the elements of the array are of equal length, which makes any array <b>much</b> easier to work with.

<lang z80> org &8000
ld hl,TestArray
call GetArrayLength_WordData_NullTerminated
call Monitor ;show registers to screen, code omitted to keep this example short
ReturnToBasic:
RET
GetArrayLength_WordData_NullTerminated:
push hl ;we'll need this later
loop_GetArrayLength_WordData_NullTerminated
ld a,(hl) ;get the low byte
ld e,a ;stash it in E
inc hl ;next byte
ld a,(hl) ;get the high byte
dec hl ;go back to low byte, otherwise our length will be off.
or a ;compare to zero.
jr nz,keepGoing
cp e ;compare to E
jr z,Terminated_GetArrayLength ;both bytes were zero.
KeepGoing:
inc hl
inc hl ;next word
jp loop_GetArrayLength_WordData_NullTerminated ;back to start
Terminated_GetArrayLength:
pop de ;original array address is in DE
or a ;clear the carry
sbc hl,de ;there is no sub hl,de; only sbc
srl h
rr l ;divide HL by 2, since each element is 2 bytes.
ret ;returns length in hl</lang>

{{out}}
<pre> (HL contains length of the array)
HL:0002
</pre>