50
SizeofDynamicStringis12byte(s).
SizeofFixedString21byte(s).
SizeofZStringis30byte(s).
SizeofWStringis60byte(s).
Output 9.4: Output of stringtype.bas
As you can see from the output, Len and Sizeof return different values. The Len
function automatically dereferences the string variables and returns the length of the
actual string, while the Sizeof function returns the length of the string variable itself. For a
dynamic string, Sizeof returns the length of the string descriptor. The string descriptor
contains a pointer to a Zstring (4 bytes), an integer containing the length of the string (4
bytes) and an integer that contains the size of the current allocation (4 bytes) which total
to 12 bytes. For fixed length string and for Zstrings, Sizeof returns the dimensioned size
of the variable. For a Wstring, the size is twice the dimensioned value because a Wstring
uses 16-bit characters rather than 8-bit characters. The Sizeof function is useful for
determining the allocation size of fixed length strings, fixed allocation Zstrings and fixed
allocation Wstrings so that you do not inadvertently lose data by trying to initialize the
variable with more data than it can hold. Dynamic strings can contain variable length
data so Sizeof is rarely used with dynamic strings.
Using String Functions with Zstring Pointers
There will be times when you will need to use a string function with a Zstring
pointer. If you try to use the pointer with directly with a string function you will receive a
Type Mismatch error from the compiler. What you need to do is to dereference the pointer
when passing the Zstring to a string function so that the function can access the string
data directly. The following program illustrates this concept.
1
2
3
4
5
6
7
8
9
10
11
12
13
OptionExplicit
DimmyZstringAsZstringPtr
myZstring=Callocate(10,Sizeof(Byte))
*myZstring="HelloFB!"
Print"Fisatposition";Instr(*myZstring,"F")
DeallocatemyZstring
Sleep
End
Listing 9.5: zstringfunc.bas
Analysis:
Line 3 dimensions a Zstring pointer, myZstring. Line 5 allocates some
space for the string data in line 6. Line 8 uses the Instr function to determine the position
104