resizing an array

Mar 27, 2013 at 6:45pm
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
Mar 27, 2013 at 6:47pm
.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.
Mar 27, 2013 at 7:00pm
@Cire

Thanks for clarifying.
Mar 27, 2013 at 7:02pm
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.
Mar 27, 2013 at 7:19pm
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 Mar 27, 2013 at 7:42pm
Mar 27, 2013 at 9:26pm
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?
Mar 28, 2013 at 11:03am

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


instead of
arr = resize_arr;
delete[] resize_arr;
Mar 28, 2013 at 5:46pm
Now that will work.
Topic archived. No new replies allowed.