I was thinking of ways to make an array larger quickly in C++ and I came up with this:
// set up arr1
int *arr1 = new int[5];
// add data to arr1
arr1[0] = 1;
arr1[1] = 2;
arr1[2] = 3;
arr1[3] = 4;
arr1[4] = 5;
// set up arr2
int *arr2 = new int[10];
arr2 = arr1; // assign arr1 to arr2
// add more values
arr2[5] = 6;
arr2[6] = 7;
arr2[7] = 8;
arr2[8] = 9;
arr2[9] = 10;
Is this even safe? I worry that this will cause some strange behavior and that arr2 is just an int[5] array and you’re now overwriting data that doesn’t belong to it.
The line
arr2 = arr1;leaks memory, and all the followingarr2[...]=lines invoke undefined behavior as they access the array of 5 ints outside of its bounds.To do what you wanted to do, replace
arr2 = arr1;withstd::copy(arr1, arr1+5, arr2);(example program: https://ideone.com/3Rohu)To do this properly, use
std::vector<int>