A Variable Length Array is an array whose size is not fixed at compile-time, but instead is decided at runtime.
- Stored on the stack (automatic storage). Their size is determined when execution reaches the declaration.
- They must be declared inside a function (block scope) or in a function prototype scope, not globally.
- VLAs were introduced in the C99 standard, some later standards (like C11) made them optional, so not all compilers may support them.
#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]);
}
}
int main()
{
int n;
printf("Enter the Size: ");
scanf("%d", &n);
printArray(n);
return 0;
}
Output
Enter the Size: 5
1 2 3 4 5
- Unlike fixed-size arrays, VLAs cannot be initialized using {0} in standard C.
- This works only for arrays with compile-time constants size, e.g, int arr[5] ={0};
#include <stdio.h>
int main()
{
int n = 5;
int arr[n] = {0};
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
Note : However, many modern compilers like GCC and Clang allow this as an extension, so they let it compile without error.
Advantages of VLAs
- Makes code more flexible than fixed-size arrays.
- No need to use dynamic memory functions (malloc/free) for temporary arrays.
- Syntax is simple and similar to normal arrays.
Disadvantages of VLAs
- VLAs are stored on the stack, which has limited memory, very large VLAs may cause stack overflow.
- Cannot be used as global or static arrays.
- Not guaranteed to be supported on all compilers (especially in modern standards like C11).