Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Dynamic arrays

When the number of elements is not known until the program runs, declare the array without bounds and give it some later with redim:

'' A dynamic array is sized, resized and freed while the program runs.
sub Show( byref label as ustring, values( ) as int32 )
    print label & " (" & lbound( values ) & " to " & ubound( values ) & "):";
    for each v in values
        print v;
    next
    print
end sub

dim values( any ) as int32         '' "any": the bounds come later
Show( "declared", values( ) )

redim values( 1 to 3 )
values( 1 ) = 10 : values( 2 ) = 20 : values( 3 ) = 30
Show( "redim", values( ) )

'' redim preserve keeps what fits; new elements start at zero.
redim preserve values( 1 to 5 )
Show( "grown", values( ) )
redim preserve values( 1 to 2 )
Show( "shrunk", values( ) )

'' Plain redim starts over: every element is zero again.
redim values( 1 to 4 )
Show( "redim again", values( ) )

'' erase frees the storage and leaves the array empty.
erase values
Show( "erased", values( ) )

'' Growing one element at a time builds a list of unknown length.
for n as int32 = 1 to 3
    redim preserve values( lbound( values ) to ubound( values ) + 1 )
    values( ubound( values ) ) = n * 100
next
Show( "appended", values( ) )

Output

declared (0 to -1):
redim (1 to 3): 10 20 30
grown (1 to 5): 10 20 30 0 0
shrunk (1 to 2): 10 20
redim again (1 to 4): 0 0 0 0
erased (0 to -1):
appended (0 to 2): 100 200 300

dim values( any ) as int32 and dim as int32 values( ) both declare an empty dynamic array. any stands for bounds that come later, and with ( any, any ) it says how many dimensions they will have.

StatementEffect
redim a( 1 to 3 )new bounds; every element is zero again
redim preserve a( 1 to 5 )new bounds; elements that still fit keep their values
erase afrees the elements; the array is empty again

Pitfall

redim without preserve is not a resize. It makes a fresh array under the same name, so redim values( 1 to 4 ) turns 10 20 into 0 0 0 0. Use redim preserve unless you mean to start over.

The last loop grows the array one element at a time, starting from empty: ubound( values ) + 1 is 0 the first time, so the first element lands at index 0. That builds a list of any length, but each redim preserve may copy every element, so for long lists the containers of the standard library are the better tool.

erase on a fixed array cannot free anything. It sets the elements back to zero and the bounds stay as they were.

Activities

  1. Read numbers into a dynamic array until one is negative, with the values coming from a fixed array instead of the keyboard.
  2. Change redim preserve values( 1 to 2 ) to plain redim and predict the line that follows.