2

When I try to run this simple code, it returns a Variable-sized object may not be initialized error. I have no idea why and how to resolve this problem.

int main()
{
    int n=0;
    n=1;
    int a[n]={}, b[n]={};
    return 0;
}
2
  • 4
    Variable length arrays are a non-standard compiler extension. You should use std::vector instead or make n const. Commented Apr 24, 2020 at 13:06
  • 1
    Does this answer your question? Variable Length Array (VLA) in C++ compilers Commented Apr 24, 2020 at 13:22

3 Answers 3

2

The array lenght must be known at compile time. Either

int a[1];

or

constexpr int n = 1;
int a[n];

Otherwise you need a dynamic array like the std container std::vector.

Sign up to request clarification or add additional context in comments.

Comments

0

You can initialize your array properly with the std::fill_n like:

std::fill_n(a, n, 0);
std::fill_n(b, n, 0);

or use std::vector like:

std::vector<int> a(n);

It will initialize all the elements to 0 by default.

Or, you can have something like:

constexpr size_t n = 10;
int a[n]{};

This will also initialize all the elements to 0.

Comments

0

Try this:

const int n=1;

int main()
{
    int a[n]={}, b[n]={};
    return 0;
}

The above code will let you create an array with length n. Note: n can't be changed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.