Variable-length array
From Wikipedia, the free encyclopedia
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).
[edit] Examples
The following C 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.