#C++ dynamic array question

2 messages · Page 1 of 1 (latest)

lofty crater
#

Say I have the follow C++ code:

int *arr = new int[5];
int *new_arr = new int[10];
delete[] arr;
arr = new_arr;
delete[] arr;

Will the final delete[] statement work properly? My thinking is that it wouldn't, because the last time arr was set using new[], it pointed to 5 ints, but now it points to 10 ints, so delete[] will only deallocate 5 ints. However, many tutorials on dynamic arrays seem to do this, so am I missing something?

cosmic fern
#

yes it'll work properly.

the new keyword will just allocate some space at some address and give that to you.

int *arr = new int[5]; // say this gives address 0x1234
int *new_arr = new int[10]; // this gives address 0x5678
delete[] arr; // deallocate 0x1234
arr = new_arr; // set arr = 0x5678
delete[] arr; // deallocate 0x5678