Saturday, January 7, 2023

GW BASIC String Descriptor address using VARPTR


When using the VARPTR function in GWBASIC it returns the address of the variable or array. Except for Strings, it returns the address of a 3 byte string descriptor. To get the address of the string we need to do some work

N$="Nick"
SA=VARPTR(N$)
PRINT PEEK(SA) 'the length of the string
PRINT PEEK(SA+1) 'lower 8 bits of address
PRINT PEEK(SA+2) 'higher 8 bits of address

to compute string address we perform the following calculation

smem#=peek(SA+2)*256+peek(SA+1) 'should point to string memory - this does what SADD function does in QBASIC/QuickBASIC

if you use integer variable % you will get an overflow. you can still convert to an integer with the following code

mem$=chr$(peek(SA+1))+chr$(peek(SA+2)) ' this converts our peek info to a 2 character string

smem%=CVI(mem$) ' we can convert the 2 character string to an integer using the CVI function without causing a buffer overflow

oh wait there is even more

now that we have the address of the string we can

print the first letter of our string by

print chr$(peek(smem%)) 'increase the smem% variable to access the other letter like smem%+1 for second letter and so on

and we can even change the string contents with poke

poke smem%,ASC("K") 'this changes N$ from Nick to Kick