In C, variable length arrays (VLAs) are also known as runtime-sized variable-sized or variable-sized arrays. The size of such arrays is defined at run-time.
Variably modified types include variable-length arrays and pointers to variable-length arrays. Variably changed types must be declared at either block scope or function prototype scope.
Variable length arrays are a feature where we can allocate an auto array (on stack) of variable size. It can be used in a typedef statement. C supports variable-sized arrays from the C99 standard. For example, the below program compiles and runs fine in C.
Syntax of VLAs in C
void fun(int size)
{
int arr[size];
// code
}
Note: In C99 or C11 standards, there is a feature called flexible array members, which works the same as the above.
Example of Variable Length Arrays
The below example shows the implementation of variable length arrays in C program
// C program to demonstrate variable length array #include <stdio.h> // function to initialize array void initialize( int * arr, int size)
{ for ( int i = 0; i < size; i++) {
arr[i] = i + 1;
}
} // function to print an array void printArray( int size)
{ // variable length array
int arr[size];
initialize(arr, size);
for ( int i = 0; i < size; i++) {
printf ( "%d " , arr[i]);
}
} // driver code int main()
{ int n = 5;
printArray(n);
return 0;
} |
1 2 3 4 5
Explanation: The above program illustrate how to create a variable size array in a function in C program. This size is passed as parameter and the variable array is created on the stack memory.