可调整大小的均匀数据结构。也称为“动态数组”。
概观
可变长度数组是
阵列,可以在程序执行期间调整大小以容纳更多或更少的元素,或者使其维数[s]使用不同的下标范围。可变长度数组用于存储其元素的内存在运行时在堆中赋值,而不是固定长度的数组,其数据赋值在程序堆栈或
.BSS或
.DATA部分中可执行,取决于它们是否使用
Static定义。
可变长度的数组也可以用作
用户定义的类型内的数据成员。与固定长度数组相反,数组不会被赋值为用户定义的类型结构的一部分,因为用户定义的类型不能是可变长度的。相反,用户定义的类型仅包含用于保存和访问场景后的可变长度数组的数组描述符,数组仍然在堆上赋值,与可变长度的数组变量一样。
可变长度数组通常称为“动态数组”,因为它们的大小可以在运行时动态变化,而不是固定大小。
宣言
使用
Dim或
ReDim关键字声明可变长度的数组,后跟一个变量标识符,括号中的边界列表和元素
数据类型.对于要声明为可变长度的数组,必须以未知边界或变量(非常量)边界声明。
ReDim总是定义可变长度的数组,指定的边界是否不变。
'' Declares a one-dimensional variable-length array of integers, with initially 2 elements (0 and 1)
ReDim a(0 To 1) As Integer
'' Declares a 1-dimensional variable-length array without initial bounds.
'' It must be resized using Redim before it can be used for the first time.
Dim b(Any) As Integer
'' Same, but 2-dimensional
Dim c(Any, Any) As Integer
Dim myLowerBound As Integer = -5
Dim myUpperBound As Integer = 10
'' Declares a 1-dimensional variable-length array by specifying variable (non-constant) boundaries.
'' The array will have myUpperBound - myLowerBound + 1 elements.
Dim d(myLowerBound To myUpperBound) As Integer
'' Declares a variable-length array whose amount of dimensions will be determined
'' by the first Redim or array access found. The array has no initial bounds and must
'' be resized using Redim before it can be used for the first time.
Dim e() As Integer
调整
调整可变长度数组的大小是指使用不同边界“重新定义”数组,从而允许数组增长或缩小。新下标范围以外的元素[s]将被删除;对象元素将被破坏。如果将数组调整为较大的大小,则新增元素将以零或
null 值初始化;对象元素是默认构造的。使用与定义相同的形式使用
ReDim关键字调整可变长度数组的大小。在这种情况下,可以从
ReDim语句中省略元素数据类型。
'' Define an empty 1-dimensional variable-length array of SINGLE elements...
Dim array(Any) As Single
'' Resize the array to hold 10 SINGLE elements...
ReDim array(0 To 9) As Single
'' The data type may be omitted when resizing:
ReDim array(10 To 19)
调整数组大小不能更改其维数,而不能更改每个维度的边界。
默认情况下,调整大小时,可变长度数组的元素值将丢失。要在调整大小期间保留以前的元素值,请使用
Preserve关键字。