117

I am having the following issue with my code:

int n = 10;
double tenorData[n]   =   {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

Returns the following error:

error: variable-sized object 'tenorData' may not be initialized

Whereas using double tenorData[10] works.

Anyone know why?

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
msmf14
  • 1,449
  • 4
  • 13
  • 19

1 Answers1

254

In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic about following the C++ standard), you can do:

int n = 10;
double a[n]; // Legal in g++ (with extensions), illegal in proper C++

If you want a "variable length array" (better called a "dynamically sized array" in C++, since proper variable length arrays aren't allowed), you either have to dynamically allocate memory yourself:

int n = 10;
double* a = new double[n]; // Don't forget to delete [] a; when you're done!

Or, better yet, use a standard container:

int n = 10;
std::vector<double> a(n); // Don't forget to #include <vector>

If you still want a proper array, you can use a constant, not a variable, when creating it:

const int n = 10;
double a[n]; // now valid, since n isn't a variable (it's a compile time constant)

Similarly, if you want to get the size from a function in C++11, you can use a constexpr:

constexpr int n()
{
    return 10;
}

double a[n()]; // n() is a compile time constant expression
j123b567
  • 3,110
  • 1
  • 23
  • 32
Cornstalks
  • 37,137
  • 18
  • 79
  • 144
  • 1
    Thank you, this is another good solution. What I really need in the end is a vector rather than an array! – msmf14 Feb 21 '13 at 22:19
  • 1
    @msmf14: Yeah, standard containers, like `vector`, are incredibly useful. – Cornstalks Feb 21 '13 at 22:21
  • Does the vector solution initialize each element when you call "std::vector<[some class]> a(n);"? – Justin Mar 23 '14 at 23:11
  • @Justin: Yes, it value-intializes (or default-constructs for `struct`s/`class`es) the elements (so `int`s/`float`s/etc will all be zero). – Cornstalks Mar 24 '14 at 14:22
  • 3
    If you're not allocating much (if it's small compared to stack size), I'd prefer using stack memory with alloca(3) and placement new. This way you don't need to worry about free'ing the memory, and memory allocation is much much faster. – holgac Apr 04 '16 at 06:59
  • 4
    +1 for mentioning that g++ allows it. Because I did not observe this error and this explains the difference. – gebbissimo Sep 27 '18 at 07:34
  • Thnx. A nice range of alternatives. – Oke Uwechue Aug 08 '19 at 21:52
  • you say that g++ allows it, but it is not proper c++. My question is how would you compile proper c++? – yolo expectz Feb 22 '20 at 14:38
  • Quick question, why this `std::vector a;` does not work? In my code snippet `int size{}; cin >> size; vector arr;` gives an error but `int size{}; cin >> size; vector arr(size);` this works. Why? – Jatin Nov 18 '20 at 13:33