Home >Backend Development >C++ >Why Does Initializing a C Array with a Variable Size Result in an Error?

Why Does Initializing a C Array with a Variable Size Result in an Error?

Susan Sarandon
Susan SarandonOriginal
2024-12-19 08:53:09786browse

Why Does Initializing a C   Array with a Variable Size Result in an Error?

Array[n] vs Array[10]: Initializing Arrays with Variable vs Numeric Literal

In C , an error occurs when initializing an array with a variable as its size, as seen in the code below:

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

The error is: "variable-sized object 'tenorData' may not be initialized." This is because variable-sized arrays are not allowed in C .

G allows this behavior as an extension, but it is not technically compliant with the C standard. To fix this issue, one can either dynamically allocate memory or use standard containers.

Dynamic Memory Allocation

int n = 10;
double* a = new double[n];

Remember to free the allocated memory using delete [] a; when finished.

Standard Containers

int n = 10;
std::vector<double> a(n);

Constant Arrays

If a proper array is desired, it can be initialized with a constant value rather than a variable:

const int n = 10;
double a[n];

In C 11, a constexpr can be used when obtaining the array size from a function:

constexpr int n()
{
    return 10;
}

double a[n()];

The above is the detailed content of Why Does Initializing a C Array with a Variable Size Result in an Error?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn