Home >Backend Development >C++ >How Can I Create a Dynamically Sized Array in C ?
Variable-Sized Array in C
Initializing an array with a variable length is not allowed in C . However, in certain implementations like G , this practice is allowed as an extension.
int n = 10; double tenorData[n] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
This code will result in an error because "tenorData" is a variable-sized object that cannot be initialized. To resolve this issue, you can specify the array size as a numeric literal:
double tenorData[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Alternative Approaches
If you truly require a dynamically sized array, C provides several options:
int n = 10; double* a = new double[n]; // ... delete[] a;
int n = 10; std::vector<double> a(n);
Constant-Sized Arrays
If a variable-sized array is not necessary, you can create a fixed-size array using a constant:
const int n = 10; double a[n];
Or, you can use a constexpr in C 11:
constexpr int n() { return 10; } double a[n()];
The above is the detailed content of How Can I Create a Dynamically Sized Array in C ?. For more information, please follow other related articles on the PHP Chinese website!