In computer programming, a variable-length array (VLA), also called variable-sized, runtime-sized, 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 Ada, Algol 68 (for non-flexible rows), APL, C99 (although subsequently relegated in C11 to a conditional feature which implementations are not required to support; on some platforms, could be implemented previously with alloca()
or similar functions) and C# (as unsafe-mode stack-allocated arrays), COBOL, Fortran 90, and J. And also Object Pascal (the language used in Borland Delphi).
Video Variable-length array
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. VLAs, like all objects in C, are limited to SIZE_MAX bytes.
Variable access
In some programming languages VLAs can be accessed via pointers, but the size can no longer be obtained when de-referenced as they are considered incomplete types.
Maps Variable-length array
Examples
The following C99 function allocates a variable-length array of a specified size, fills it with floating-point values, and then passes it to another function for processing. Because the array is declared as an automatic variable, its lifetime ends when read_and_process()
returns.
In C99, the length parameter must come before the variable-length array parameter in function calls.
Following is the same example in Ada. Ada arrays carry their bounds with them, so there is no need to pass the length to the Process function.
The equivalent Fortran 90 function is:
when utilizing the Fortran 90 feature of checking procedure interfaces at compile-time; on the other hand, if the functions use pre-Fortran 90 call interface the (external) functions must first be declared, and the array length must be explicitly passed as an argument (as in C):
The following COBOL fragment declares a variable-length array of records, DEPT-PERSON
, having a length (number of members) specified by the value of PEOPLE-CNT
.
The following C# fragment declares a variable-length array of integers. The "unsafe" keyword would require an assembly containing this code to be marked as unsafe.
Dynamic vs. automatic
Languages such as Java and .NET Framework are not considered to provide variable-length arrays, because all array objects in those languages are logically allocated on the heap, and therefore do not have automatic storage duration for arrays. (Java and dotNet compilers can optimize these heap allocations to actually be on the stack where possible.)
References
Source of the article : Wikipedia