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:

  1. Using malloc() Function
  2. Using calloc() Function
  3. Resizing Array Using realloc() Function
  4. Using Variable Length Arrays(VLAs)
  5. Using Flexible Array Members

Similar Reads

1. Dynamic Array Using malloc() Function

The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. It is defined inside header file....

2. Dynamic Array Using calloc() Function

...

3. Dynamically Resizing Array Using realloc() Function

The “calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified number of blocks of memory of the specified type and initialized each block with a default value of 0....

4. Variable Length Arrays(VLAs)

...

5. Flexible Array Members

The “realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a previously allocated memory....