C++ Program to Implement Variable Length Array



Variable length arrays can have a size as required by the user i.e they can have a variable size.

A Variable?Length Array (VLA) is an array whose length is determined at runtime (not compile-time).

Variable Length Array Using Vector

A vector is defined by the resizable array that is part of data structures and is used to store multiple elements from the same data type. A variable length array can be created using the Vector.

Syntax

Following are the syntaxes that uses to modify the size dynamically using vector ?

// inserting the array element
push_back()

and,

// deleting the array element
pop_back()

Example

In this example, we used the basic operations on a vector such as inserting and deleting elements.

#include <iostream>
#include <vector>
using namespace std;

int main() {
   
   // Initialize the array elements
   vector<int> arr = {10, 20, 30, 40, 50}; 
   
   // inserting array element
   arr.push_back(60);  
   
   // deleting array element
   arr.pop_back();     
   
   // Access elements
   cout << "Vector elements: ";
   for (int num : arr) {
       cout << num << " ";
   }
   
   return 0;
}

Output

The above code produces the following output ?

Vector elements: 10 20 30 40 50 

Variable Length Array Using Dynamic Allocation (new[]/delete[])

In C++, dynamic allocation allows user to create a run time sized arrays in the heap memory. To avoid the risks it's prefer vector to perform fixed sized arrays.

Example

In this program, we dynamically allocates an integer array to the heap and initializes with its values. Then display the array element by deallocates the memory using delete[].

#include <iostream>
using namespace std;

int main() {
   const int size = 5;
   
   // Heap allocation
   int* arr = new int[size]{10, 20, 30, 40, 50}; 
   
   // Access elements
   cout << "Heap array: ";
   for (int i = 0; i < size; ++i) {
       cout << arr[i] << " ";
   }
   
   delete[] arr; 
   return 0;
}

Output

The above program produces the following output ?

Heap array: 10 20 30 40 50 
Updated on: 2025-04-09T19:05:12+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements