Can someone explain to me why should we declare "new double" ?

Hello guys,
I'm a beginner at c++ and in a few days I have an exam but there are some things I don't understand in the example cpp file that my teacher sent me.
So I would like to ask for help. Can some one explain to me what is the meaning of declaring a " new double " and why should we delete it at the end ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;
int main(){
    double v[]={-37,280,-.45}, y=-17;
    double *x[]={v+2,&y,new double[2]}; // What's the meaning of new double ? 
    x[2][0]=123;
    x[2][1]=4;
    double **g=x+1, ***s=&g, **z=new double*;
    *z=&y;
    cout<<"v[0] == "<<v[0]<<endl; 
    *(*(*s-1)-2)=65;
    cout<<"v[0] == "<<v[0]<<endl; 
    cout<<"**(g+1) == "<<**(g+1)<<endl; 
    cout<<"(g+1)[1] == "<<(*(g+1))[1]<<endl; 
    cout<<"**z == "<<**z<<endl; 
    cout<<"**g == "<<**g<<endl; 
	delete[] x[2]; // Why should we delete it ? 
	delete z; // Why should we delete it ? 
    return 0;
}
double *x[]={v+2,&y,new double[2]};

x is an array of pointers to doubles. It is 3 elements big.

x[0] is the address of v[2]

x[1] is the address of y

new double[2] allocates an array of double of size 2 from the heap. That value is assigned to x[2]. So it's valid to do x[2][0] and x[2][1] to get to these values.
Last edited on
everything kbw said, plus you have to delete everything that you new.

new will allocate memory, delete will deallocate it. if you just new without delete then you will keep allocating without deallocating, and eventually consume all of your memory.

we call it "memory leak" and it is BAD!
Ok, now I get it thank you guys.
Topic archived. No new replies allowed.