how to create an 'n' sized array in c++?

Viewed 126

I'm trying to create an array of n size, but everytime I try to do that I get an error saying:

expression must have a constant value -- the value of variable "n" (declared at line 33) cannot be 
used as a constant

I worked like this before but that was on codeblocks. This time I've downloaded mingw manually and have been working in VSCode. All my other codes work fine but cant seem to find a solution for this.

int main()
{
    int n;
    cin >> n;
    int arr[n];
    for (int i = 0; i < n; i++)
    {
        cin >> arr[i];
    }
    for (int i = 0; i < n; i++)
    {
        cout << arr[i];
    }
}

Basic Setup of Mingw

Basic Setup of Mingw

My gcc version is:

gcc.exe (MinGW.org GCC Build-2) 9.2.0
2 Answers

int arr[n]; is invalid C++ with runtime n, it uses VLA extension.

use std::vector instead:

int n;
std::cin >> n;
std::vector<int> arr(n);

You can create array with length of n using heap/ dynamic array. like: int arr= new array(n)

Related