Reputation: 519
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;
}
Upvotes: 2
Views: 128
Reputation:
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.
Upvotes: 0
Reputation: 1321
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.
Upvotes: 2
Reputation: 12263
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.
Upvotes: 0