2

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;
}
1

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

In this context what does it mean for something to be legal? Both methods work. What I'm trying to understand is the reason why I would use the pointer?
@Rambi: the second one does not work on most C++ compilers. You are probably using g++ where it works.
0

Dynamic allocation allow you a lot of things.

  • First of all, you can return this array from the function where it is create.

  • Strict C(C89) does not allow dynamic stack allocation. double x[n] will throw error on many compilers.

2 Comments

"Strict C does not allow dynamic stack allocation" incorrect. C99 added variable length arrays
I believe that Tom meant C89 «Strict C». Not to mention the post is about C++, obviously. And VLAs are really poorly defined, that's one of the easiest ways to obtain self-destructive behavior in programs.
0

Dynamically allocated arrays won't cause Stack Overflow if they're too big.

The pointer lives on the stack, but the contents live on the heap. The downsides, however, include slower access due to an indirection, possible memory leaks and more impenetrable code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.