Kanzaki Aria Echo
Kanzaki Aria Echo

Reputation: 29

How to make the array size correct in C++?

I'm trying to create an array and the size of the array depends on the user input. But there is an error in my code, It said: "expression must have a constant value".

Here is my code:

#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
    int var;
    cout << "What size do you want to choose: "<< endl;
    cin >> var;

    int arr[var];
}

How can I change my code and make it work?

Upvotes: 0

Views: 195

Answers (4)

aviad
aviad

Reputation: 8278

Arrays in C++ must have constant size known at compile-time. You can preallocate several constant sizes known at compile time and offer the user to choose one of them. Alternatively, you can use another data structure that allows dynamic size allocation e.g std::vector. Good luck!

Upvotes: 0

acraig5075
acraig5075

Reputation: 10756

How can I change my code and make it work?

Change

int arr[var];

to

std::vector<int> arr(var);

This will require #include <vector>

Upvotes: 4

Muhammad Shahjad
Muhammad Shahjad

Reputation: 112

To allocate an array dynamically, we use the array form of new and delete (often called new[] and delete[]):

#include <iostream>

int main()
{
    std::cout << "Enter a positive integer: ";
    int length{};
    std::cin >> length;

    int *array{ new int[length]{} }; // use array new.  Note that length does not need to be constant!

    std::cout << "I just allocated an array of integers of length " << length << '\n';

    array[0] = 5; // set element 0 to value 5

    delete[] array; // use array delete to deallocate array

    // we don't need to set array to nullptr/0 here because it's going to go out of scope immediately after this anyway

    return 0;
}

Upvotes: 0

Remy Lebeau
Remy Lebeau

Reputation: 598309

The syntax you are using is known as a "variable length array", and is NON-STANDARD. Only a few compilers support it as an vendor-specific extension to the C++ language.

A standard compliant fixed-length array must have its size known to the compiler as a compile-time constant.

For what you want, you need to use the new[] operator instead:

int *arr = new int[var];
...
delete[] arr;

Or better, use a std::vector container:

#include <vector>

std::vector<int> arr(var);

Upvotes: 3

Related Questions