ReDim Command

Purpose

Reallocates storage space for a dynamic array.

Syntax

ReDim varname(subscripts) [As type] [, varname(subscripts) [As type]] . . .

varname: variable name
subscripts: dimensions of an array

Description

The ReDim statement is used to size or resize a dynamic array that has already been formally declared using a Global, Public, Local or Dim statement with or without empty parentheses (without dimension subscripts).

You can use the ReDim statement repeatedly to change the number of elements and dimensions in an array. However, you can not declare an array of one data type and later use ReDim to change the array to another data type.

ReDim does not clear the elements from the array, so data will remain in the elements that exist before and after redim-ing. To explicitly erase all elements use Erase before redim-ing, then no old data will be passed to the new redim-ed array.

Example

Dim MyArray() As Integer   ' Declare dynamic array.

ReDim MyArray(5)          ' Allocate 5 elements.

Local a() As String

ReDim a(10 To 50)

Erase a() : ReDim a(10 .. 50)

ReDim a(10 ... 50, -1 To 9)

Remarks

Dim a() As Int : ReDim a(count) requires an additional 72 bytes of (stack) memory compared to Dim a(count).

GFA-BASIC 32 doesn't provide the Preserve keyword, because the data of the array isn't erased.

An array in a Variant cannot be redimmed:

Dim v = Array(1, 2, "Hello") : ReDim v(5) // not possible

Known Issues

An array, when first dimensioned, and unless otherwise stated, takes its lower boundary (or LBound) from the value of Option Base; however, when that array is ReDim'ed, both the existing LBound value and the value of Option Base are ignored and the lower boundary is set to zero, unless explicitly set otherwise within the ReDim statement. This is shown in the example below:

Option Base 1

Dim a%(10), b$(1 To 10), c&(-4 To 100)

Print LBound(a%()), LBound(b$()), LBound(c&()) // Prints 1  1 -4

ReDim a%(10), b$(10), c&(100)

Print LBound(a%()), LBound(b$()), LBound(c&()) // Prints 0  0  0

This can cause some odd effects, such as when sorting the array in question. To get around this bug, if an array was dimensioned with a lower boundary other than zero (through Option Base or otherwise), then, when redim'ing, explicitly specify the lower boundary in the ReDim statement like this:

ReDim a%(1 To 10), b$(1 To 10), c&(-4 To 100)

Print LBound(a%()), LBound(b$()), LBound(c&()) // Prints 1  1 -4

See Also

Dim, Dim?, Erase

{Created by Sjouke Hamstra; Last updated: 04/03/2017 by James Gaite}