Suslik
Suslik

Reputation: 1071

delete dynamic array

I have to write a program, where i use dynamic arrays:

int size=1;
double* dyn_arr = new double[size];

int n=0; 
double sum=0.0;
while(std::cin >> dyn_arr[n]){
    sum = sum + dyn_arr[n++];
    if(n==size){
        size*=2;
        double* new_array = new double[size];
        std::copy(dyn_arr, dyn_arr + n, new_array);
        delete[] dyn_arr;
        dyn_arr = new_array;
    }
}

I can't understand the part dyn_arr = new_array after delete[] dyn_arr. dyn_arr is a pointer on the first element of the array dyn_arr, isn't it? How can i delete the pointer/array and write again dyn_arr = new_array ?

Upvotes: 1

Views: 1586

Answers (3)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

delete[] dyn_arr;

You're not "deleting the pointer". You're "deleting" the memory that it used to point to. Now it points to nothing. It's dangling.

dyn_arr = new_array;

Now you're making the pointer point to the new block of memory, instead.

Upvotes: 3

Karl Nicoll
Karl Nicoll

Reputation: 16419

new_array is a new dynamic array that was created inside your if statement. The lines in question are deleting the original array, and then assigning dyn_array to point to the new array.

delete[] dyn_arr;     // <--- Delete the old array.
dyn_arr = new_array;  // <--- Point dyn_arr at the newly allocated array.

Upvotes: 1

David Schwartz
David Schwartz

Reputation: 182761

The dyn_arr variable is a variable of type "pointer to double". That means it holds the address of a double and you can change which double it points to whenever you want.

double* dyn_arr = new double[size];

Now, dyn_arr points to the first of size doubles.

double* new_array = new double[size];

This creates a new variable of type "pointer to double" that points to the first of a new array of doubles.

delete[] dyn_arr;

This deletes the array of doubles dyn_arr points to. Since we got dyn_arr's value from new[], we can pass it to delete[] when we're done with the array. So now dyn_arr points to garbage and we mustn't use its value.

dyn_arr = new_array;

This changes the value of dyn_arr so it points to the new set of doubles we allocated. Since dyn_arr is a variable of pointer type, we can change it to point to different things whenever we want.

Upvotes: 5

Related Questions