Simulating Integer Arrays

Author(s): Nels Anderson
Publication: Syntax
Pub Details: Syntax/Syntax ZX80 v3 n4 (Volume 3, Issue 4)
Date: April 1982
Pages: 8

Many BASICs use integer variables to save memory. The ZX81 has only floating point variables, but you can simulate integer arrays with small values using PEEK and POKE. This technique only stores values between 0 and 255, but saves lots of memory with large arrays not requiring large values.

To use an integer array, first reserve space for it. Put a REM line as the first program line, followed by spaces equal to the size of the array. You can also reserve space by changing the ZX81 system variable RAMTOP (see manual, chaps. 26-28). This two-byte value at 16388 and 16389 normally holds 17407 with 1K RAM. To reserve X bytes at the top of RAM, enter:

POKE 16388,INT((17407-X)/256)
POKE 16389,X-INT((17407-X)/256)
NEW or CLEAR

The first byte of the array will be at location 17407-X. If you use a REM, it must be the first line and the array starts at 16514.

You can access any position in a one-dimensional array by PEEKing or POKEing at an address = (the starting address + the desired position – 1). For example, to print location I in array U, you normally have:

 100 PRINT U(I)

Use the following instead:

   1 REM ............
10 LET U=16513
100 PRINT PEEK(U+I)

Note that U is defined as array start – 1 to save a calculation each time the array is accessed.

Two-dimensional arrays are equally simple. For example, to print location I,J in array V you normally have:

 100 PRINT V(I,J)

Use the following instead:

   1 REM .............
10 LET V=16505
100 PRINT PEEK(V+8*I+J)

This example assumes that the I dimension of the array is 8. So V becomes 16514 – 8 (the first dimension of the array) – 1 and I is multiplied by 8 each time the array is PEEKed or POKEd. Any other value can be used as well.

To show how much space this method can save, say the array V in the last example was set up by DIM V(8,8). This ZX81 floating point array takes up 8x8x5, or 320 bytes of memory for data since each value is stored as 5 bytes. By setting up your own array you need only 8×8 or 64 bytes–a significant savings!

You also save space by setting a variable equal to the array’s starting address as in our examples. The ZX81 uses 11 bytes to store the starting address in each PEEK or POKE where it’s used (1 byte for each of 5 digits in the number, plus a special character, plus 5 digits for the floating point value). But a variable name only takes 1 byte to store.