123

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?

4
  • 4
    It would help to give a language. In C++ your arrays of that form need to have a compile-time constant size. Commented Feb 21, 2013 at 22:04
  • C++, using Codeblocks with the mingw32-g++ compiler! Commented Feb 21, 2013 at 22:05
  • Thanks, Justin and @AndrewVarnerin, that solved it! added const before the int: const int n = 10; Solved! Commented Feb 21, 2013 at 22:07
  • stackoverflow.com/questions/1887097/variable-length-arrays-in-c Commented Dec 4, 2014 at 9:50

1 Answer 1

265

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
Sign up to request clarification or add additional context in comments.

9 Comments

Thank you, this is another good solution. What I really need in the end is a vector rather than an array!
@msmf14: Yeah, standard containers, like vector, are incredibly useful.
Does the vector solution initialize each element when you call "std::vector<[some class]> a(n);"?
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.
+1 for mentioning that g++ allows it. Because I did not observe this error and this explains the difference.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.