Variable-length array


In programming, a variable-length array (or VLA) is an array data structure of automatic storage duration whose length is determined at run time (instead of at compile time).

Programming languages that support VLAs include APL, COBOL, and C (added in C99).

Memory Allocation

One problem that may be hidden by a language's support for VLAs is that of the underlying memory allocation: in environments where there is a clear distinction between a heap and a stack, it may not be clear which, if any, of those will store the VLA.

For example, the Gnu C Compiler allocates memory for VLAs on the stack.

Examples

The following C99 function allocates a variable-length array of a specified size, fills it with floating-point values, then passes it to another function for processing. Because the array is declared as an automatic variable, its lifetime ends when the read_and_process function returns.

float read_and_process(int n)
{
    float   vals[n];
 
    for (int i = 0; i < n; i++)
        vals[i] = read_val();
    return process(vals, n);
}

The following COBOL fragment declares a variable-length array of records.

DATA DIVISION.
WORKING-STORAGE SECTION.
01  VAR-ITEM.
    05  VAR-CNT         PIC S9(4) BINARY.
    05  VAR-PERSON      OCCURS 0 TO 20 TIMES DEPENDING ON VAR-CNT.
        10  VAR-NAME    PIC X(20).
        10  VAR-WAGE    PIC S9(7)V99 PACKED-DECIMAL.

Languages such as C# and Java do not have variable-length arrays, because all arrays in those languages are dynamically allocated on the heap and therefore do not have automatic storage duration.








stock | retire | vm
Why are we here?
All text is available under the terms of the GNU Free Documentation License
This page is cache of Wikipedia. History