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
Release: 2025-01-05 13:06:49
Original
184 people have browsed it

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};
Copy after login

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};
Copy after login

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;
Copy after login
  • Standard Containers: Using standard containers like std::vector.
int n = 10;
std::vector<double> a(n);
Copy after login

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];
Copy after login

Or, you can use a constexpr in C 11:

constexpr int n()
{
    return 10;
}

double a[n()];
Copy after login

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template