Home >Backend Development >C++ >Array Initialization in C : `Array[n]` vs. `Array[10]` – What's the Difference?
Array[n] vs Array[10]: The Distinction Between Variable Initialization and Numeric Literals for Array Sizes
In C programming, arrays play a crucial role in data storage and retrieval. However, there can be certain pitfalls when working with array initialization, especially related to the use of variable-length arrays.
Consider the following code snippet:
int n = 10; double tenorData[n] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
This code aims to initialize an array named tenorData with a size determined by the variable n, which is set to 10. However, this approach raises a compilation error stating that the variable-sized object tenorData cannot be initialized in this manner.
The key difference in this code lies in the use of a variable, n, to define the size of the array. In C , variable length arrays are not supported, meaning that the size of an array must be a known constant at compile time.
To resolve this issue and successfully initialize the array, there are several options available:
double tenorData[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
const int n = 10; double tenorData[n] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int n = 10; double* tenorData = new double[n];
Remember to deallocate memory using delete [] tenorData when you are finished with the array.
int n = 10; std::vector<double> tenorData(n);
By following these guidelines, you can effectively initialize arrays in C while avoiding the pitfalls associated with variable-length arrays.
The above is the detailed content of Array Initialization in C : `Array[n]` vs. `Array[10]` – What's the Difference?. For more information, please follow other related articles on the PHP Chinese website!