Variable Length Arrays(VLAs)
Variable length arrays or VLAs, are those arrays in which we can determine the size of the array at the run time. It allocates the memory in the stack and it’s based on the local scope level.
The size of a variable length array cannot be changed once it is defined and using variable length array as its found down sides as compared to above methods.
Example:
C
// C program to demonstrate the use of VLAs #include <stdio.h> int main() { int n; printf ( "Enter the size of the array: " ); scanf ( "%d" , &n); int arr[n]; printf ( "Enter elements: " ); for ( int i = 0; i < n; ++i) { scanf ( "%d" , &arr[i]); } printf ( "Elements of VLA of Given Size: " ); for ( int i = 0; i < n; ++i) { printf ( "%d " , arr[i]); } return 0; } |
Output:
Enter the size of the array: 5 Enter elements: 1 2 3 4 5 Elements of VLA of Given Size: 1 2 3 4 5
To know more about variable length arrays, please refer to the article –Variable Length Arrays in C/C++.
Dynamic Array in C
Array in C is static in nature, so its size should be known at compile time and we can’t change the size of the array after its declaration. Due to this, we may encounter situations where our array doesn’t have enough space left for required elements or we allotted more than the required memory leading to memory wastage. To solve this problem, dynamic arrays come into the picture.
A Dynamic Array is allocated memory at runtime and its size can be changed later in the program.
We can create a dynamic array in C by using the following methods:
- Using malloc() Function
- Using calloc() Function
- Resizing Array Using realloc() Function
- Using Variable Length Arrays(VLAs)
- Using Flexible Array Members