resizing an array

int size = 10;
int* arr = new int[size];

void resize()
{
int* resize_arr = new int[size + 1];
for(int i = 0; i < size; i++)
resize_arr[i] = arr[i];

size++;
arr = resize_arr;
delete[] resize_arr;
}

i came across this code to dynamically resize an array...and here in the last statement they have deleted resize_arr.As resize_arr and arr points to samething...i think that memory that arr pointing to is also deleted...iguess correct thing would be delete [] arr....before we assign resize_arr pointer to arr...!! i am new to c++...please help....thanks
.i think that memory that arr pointing to is also deleted...iguess correct thing would be delete [] arr....before we assign resize_arr pointer to arr...!!

You are correct on both counts.
@Cire

Thanks for clarifying.
Well, in fact you don't need the lign

delete[] resize_arr;

because resize_arr will be discarded from memory anyway when your function returns.
The pointer resize_array will be deleted. The int objects will be leaked if you don't delete dynamically assigned memory. When a functions goes out of scope it cleans up memory allocated to the stack. Objects declared in heap memory have no scope. It is the programmers job to release the memory the occupied. Since the pointer is destroyed there is no fear of a dangling pointer and therefore no need to assign resize_array = 0; when you call the delete.
Last edited on
I have a question about this code
1
2
arr = resize_arr;
delete[] resize_arr;

If you assign resized array to arr where do you remember the addres of the old array, which I don't see where you deleted?
And dosen't delete[] resize_arr; delite your new array insted of the old one?

@zoran
actually last two lines should be written as
delete [] arr;
arr=resize_arr;


instead of
arr = resize_arr;
delete[] resize_arr;
Now that will work.
Topic archived. No new replies allowed.