ReDim
 
Defines or resizes a variable-length array

Syntax

ReDim [ Shared ] [ Preserve ] symbolname([subscript [, ...]]) As datatype [, ...]
ReDim [ Shared ] [ Preserve ] As datatype symbolname([subscript [, ...]]) [, ...]

Parameters

Shared
Specifies shared (file-scope) access to the array throughout the module.
Preserve
When used with an existing array, the contents of the array will be preserved during the resize. Note that Preserve will not work properly in all cases.
symbolname
A new or existing array id.
subscript: [ lowerbound To ] upperbound
The lower and upper bound range for a dimension of the array. Lower bound defaults to zero (0), or the default Base, if not specified.
datatype
The type of elements contained in the array.

Description

ReDim can be used to define new variable-length arrays, or resize existing variable-length arrays. ReDim always produces variable-length arrays, so, unlike Dim, variable-length arrays can be defined with constant subscripts.

When defining a new variable-length array, its elements are default constructed. For simple data types like Integer or Double, the elements are initialized to zero (0). For user-defined types with a default constructor, that will be called.

NOTES:
  • ReDim Preserve may not work as expected in all cases:
Preserve's current behavior is to keep the original data contiguous in memory, and only expand or truncate the size of the memory.
Its behavior (with a single dimension) is well-defined only when the upper bound is changed. If the lower bound is changed, the current result is that the data is in effect shifted to start at the new lower bound.
With multiple dimensions, only the upper bound of only the first dimension may be safely increased. If the first dimension is reduced, the existing mappable data may be lost. If lower-order dimensions are resized at all, the effects can be hard to predict.

  • ReDim cannot be used on fixed-size arrays - i.e. arrays with constant bounds made with Dim. This includes arrays contained in UDTs (user-defined Types), because currently only fixed-size arrays are supported in UDTs. This also includes fixed-length arrays passed as parameters in a function. FreeBASIC cannot prevent you trying this at compile-time, but the results at run-time will be undefined.

  • Using ReDim within a member procedure with an array that contains an instance of the object class is undefined, and will [hopefully] result in horrible crashes.

Example

'' Define a variable-length array with 5 elements
''
ReDim array(0 To 4) As Integer

For index As Integer = LBound(array) To UBound(array)
    array(index) = index
Next

'' Resize a variable-length array with 10 elements 
'' (the lower bound should be kept the same)
ReDim Preserve array(0 To 9) As Integer

Print "index", "value"
For index As Integer = LBound(array) To UBound(array)
    Print index, array(index)
Next

This program will produce the following output:

index         value
 0             0
 1             1
 2             2
 3             3
 4             4
 5             5
 6             0
 7             0
 8             0
 9             0

'' Define a variable-length array
Dim array() As Integer

'' ReDim array to have 3*4 elements
ReDim array(1 To 3, 1 To 4)

Dim As Integer n = 1, i, j

Print "3 * 4:"
Print
For i = LBound(array, 1) To UBound(array, 1)
    For j = LBound(array, 2) To UBound(array, 2)
        array(i, j) = n
        Print Using "##  "; array(i, j);
        n += 1
    Next
    Print
Next
Print


'' ReDim Preserve array to have 4*4 elements, preserving the contents
'' (only the first upper bound should be changed)
ReDim Preserve array(1 To 4, 1 To 4) As Integer

Print "4 * 4:"
Print
For i = LBound(array, 1) To UBound(array, 1)
    For j = LBound(array, 2) To UBound(array, 2)
        Print Using "##  "; array(i, j);
    Next
    Print
Next
Print


'' ReDim Preserve array to have 2*4 elements, preserving but trancating the contents
'' (only the first upper bound should be changed)
ReDim Preserve array(1 To 2, 1 To 4) As Integer

Print "2 * 4:"
Print
For i = LBound(array, 1) To UBound(array, 1)
    For j = LBound(array, 2) To UBound(array, 2)
        Print Using "##  "; array(i, j);
    Next
    Print
Next
Print

This program will produce the following output:

3 * 4:

 1   2   3   4
 5   6   7   8
 9  10  11  12

4 * 4:

 1   2   3   4
 5   6   7   8
 9  10  11  12
 0   0   0   0

2 * 4:

 1   2   3   4
 5   6   7   8

Differences from QB

  • Preserve was in Visual Basic, but not in QBASIC.
  • Multi-dimensional arrays in FreeBASIC are in row-major order, rather than column-major order.

See also

Сайт ПДСНПСР. Если ты патриот России - жми сюда!


Знаете ли Вы, что, когда некоторые исследователи, пытающиеся примирить релятивизм и эфирную физику, говорят, например, о том, что космос состоит на 70% из "физического вакуума", а на 30% - из вещества и поля, то они впадают в фундаментальное логическое противоречие. Это противоречие заключается в следующем.

Вещество и поле не есть что-то отдельное от эфира, также как и человеческое тело не есть что-то отдельное от атомов и молекул его составляющих. Оно и есть эти атомы и молекулы, собранные в определенном порядке. Также и вещество не есть что-то отдельное от элементарных частиц, а оно состоит из них как базовой материи. Также и элементарные частицы состоят из частиц эфира как базовой материи нижнего уровня. Таким образом, всё, что есть во вселенной - это есть эфир. Эфира 100%. Из него состоят элементарные частицы, а из них всё остальное. Подробнее читайте в FAQ по эфирной физике.

НОВОСТИ ФОРУМАФорум Рыцари теории эфира
Рыцари теории эфира
 10.11.2021 - 12:37: ПЕРСОНАЛИИ - Personalias -> WHO IS WHO - КТО ЕСТЬ КТО - Карим_Хайдаров.
10.11.2021 - 12:36: СОВЕСТЬ - Conscience -> РАСЧЕЛОВЕЧИВАНИЕ ЧЕЛОВЕКА. КОМУ ЭТО НАДО? - Карим_Хайдаров.
10.11.2021 - 12:36: ВОСПИТАНИЕ, ПРОСВЕЩЕНИЕ, ОБРАЗОВАНИЕ - Upbringing, Inlightening, Education -> Просвещение от д.м.н. Александра Алексеевича Редько - Карим_Хайдаров.
10.11.2021 - 12:35: ЭКОЛОГИЯ - Ecology -> Биологическая безопасность населения - Карим_Хайдаров.
10.11.2021 - 12:34: ВОЙНА, ПОЛИТИКА И НАУКА - War, Politics and Science -> Проблема государственного терроризма - Карим_Хайдаров.
10.11.2021 - 12:34: ВОЙНА, ПОЛИТИКА И НАУКА - War, Politics and Science -> ПРАВОСУДИЯ.НЕТ - Карим_Хайдаров.
10.11.2021 - 12:34: ВОСПИТАНИЕ, ПРОСВЕЩЕНИЕ, ОБРАЗОВАНИЕ - Upbringing, Inlightening, Education -> Просвещение от Вадима Глогера, США - Карим_Хайдаров.
10.11.2021 - 09:18: НОВЫЕ ТЕХНОЛОГИИ - New Technologies -> Волновая генетика Петра Гаряева, 5G-контроль и управление - Карим_Хайдаров.
10.11.2021 - 09:18: ЭКОЛОГИЯ - Ecology -> ЭКОЛОГИЯ ДЛЯ ВСЕХ - Карим_Хайдаров.
10.11.2021 - 09:16: ЭКОЛОГИЯ - Ecology -> ПРОБЛЕМЫ МЕДИЦИНЫ - Карим_Хайдаров.
10.11.2021 - 09:15: ВОСПИТАНИЕ, ПРОСВЕЩЕНИЕ, ОБРАЗОВАНИЕ - Upbringing, Inlightening, Education -> Просвещение от Екатерины Коваленко - Карим_Хайдаров.
10.11.2021 - 09:13: ВОСПИТАНИЕ, ПРОСВЕЩЕНИЕ, ОБРАЗОВАНИЕ - Upbringing, Inlightening, Education -> Просвещение от Вильгельма Варкентина - Карим_Хайдаров.
Bourabai Research Institution home page

Боровское исследовательское учреждение - Bourabai Research Bourabai Research Institution