Benefit of using pointers for dynamic memory allocation with arrays

advertisements

I am trying to understand the benefit using this...

double *x = new double[n];

instead of just using this...

double x[n];

Thanks

#include <iostream>

using namespace std;

main()
{
    int n;
    cout<<"# of elements in array"<<endl;
    cin>>n;

    double *x = new double[n]; //or double x[n]

    int i;

    for(i=0;i<n;i++)
    {
        cout<<x[i]<<endl;
    }
    return 0;
}


Mandatory note:

std::vector<double> x(n);

beats what you have there.

Actual answer:

The benefit is that

double *x = new double[n];

is legal, whereas

double x[n];

is not, unless n is a compile-time constant (in your case, it's not).

C++ doesn't support variable-length-arrays.