Home >Backend Development >C++ >How Can I Create a Dynamically Sized Array in C ?

How Can I Create a Dynamically Sized Array in C ?

Linda Hamilton
Linda HamiltonOriginal
2025-01-05 13:06:49137browse

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:

  • Dynamic Memory Allocation: Manual allocation using new and delete[].
int n = 10;
double* a = new double[n];
// ...
delete[] a;
  • Standard Containers: Using standard containers like std::vector.
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!

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