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;
}
Jarod42
  • 190,553
  • 13
  • 166
  • 271
Qiu YU
  • 511
  • 4
  • 19
  • 4
    Variable length arrays are a non-standard compiler extension. You should use [`std::vector`](https://en.cppreference.com/w/cpp/container/vector) instead or make `n` `const`. – 0x5453 Apr 24 '20 at 13:06
  • 1
    Does this answer your question? [Variable Length Array (VLA) in C++ compilers](https://stackoverflow.com/questions/39334435/variable-length-array-vla-in-c-compilers) – bitmask Apr 24 '20 at 13:22

3 Answers3

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.

Icebone1000
  • 1,200
  • 4
  • 12
  • 24
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.

NutCracker
  • 10,520
  • 2
  • 39
  • 66
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.