Implementation of Variable-Length Arrays

Variable-length Arrays are the arrays whose size gets evaluated at the runtime. Therefore, the size can take a variable expression. The size of the static length arrays, on the other hand, gets determined at the compile time, and for this reason, the length is fixed.

How to implement Variable-Length Arrays?

Programming languages such as Java, Python, and C (from C99 standard) support VLAs. Consider the following code in Java.

int n=5;
int[] arr= new int[n];

The above code creates a variable-sized array in Java because the length is a variable n.

Consider the code below that is valid in the C language (from C99 standard).

#include <stdio.h>

int main()
{
   int n=5;
   int array[n];
   
}

C++, on the other hand, did not support variable-length arrays before C++14. The following code will throw an error till the C++11 standard.

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

int main()
{
    int n = 5;
    int arr[n];

}

Output

Implementation

We can write a program that implements variable-length arrays in C++, Java, Python, or C. Consider the following code.

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

int main()
{
    int n;
    int* arr;
    cout << "Enter array size" << endl;
    cin >> n;
    arr = new int[n];
    int sum = 0;
    for (int i = 0;i < n;i++) {
        cout << "Enter an integer:";
        cin >> arr[i];
        sum += arr[i];
    }
    float average = float(sum) / float(n);
    cout << "The average of the numbers entered: " << average << endl;


}

Output

In the above example, we take an average of integers taken from the user. These numbers are stored in an array. It will be variable-sized because the length of the array will get decided at runtime. We create an array with the new keyword, i.e., new int[n], and it is assigned to the integer pointer arr. Note that we take n from the user here.

Back to: Data Structure > Data Structure - Arrays

Leave a Reply

Your email address will not be published. Required fields are marked *