Variable Length Arrays (VLAs) in C
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
#include <stdio.h>
void initialize( int * arr, int size)
{
for ( int i = 0; i < size; i++) {
arr[i] = i + 1;
}
}
void printArray( int size)
{
int arr[size];
initialize(arr, size);
for ( int i = 0; i < size; i++) {
printf ( "%d " , arr[i]);
}
}
int main()
{
int n = 5;
printArray(n);
return 0;
}
|
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.
Last Updated :
08 Jan, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...