Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array[n] vs Array[10] - Initializing array with variable vs real number

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?

like image 203
msmf14 Avatar asked Feb 21 '13 22:02

msmf14


People also ask

Can you initialize an array with a variable?

You initialize an array variable by including an array literal in a New clause and specifying the initial values of the array. You can either specify the type or allow it to be inferred from the values in the array literal.

What are the different types of initializing an array?

There are two ways to specify initializers for arrays: With C89-style initializers, array elements must be initialized in subscript order. Using designated initializers, which allow you to specify the values of the subscript elements to be initialized, array elements can be initialized in any order.

How would you declare and initialize an array of 10 inch?

Array Initialization in Java To use the array, we can initialize it with the new keyword, followed by the data type of our array, and rectangular brackets containing its size: int[] intArray = new int[10]; This allocates the memory for an array of size 10 . This size is immutable.

What is the array and initializing arrays?

Single Dimensional Array Initialization. The process of assigning values to the array elements is called array initialization. Once an array is declared, its elements must be initialized before they can be used in the program. If they are not properly initialized the program produces unexpected results.


1 Answers

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 
like image 101
Cornstalks Avatar answered Sep 23 '22 22:09

Cornstalks