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 ?
delete[] dyn_arrthe array wheredyn_arrpointed to is freed anddyn_arris a dangling pointer. you can reassign to this pointer, e.g.nullptror a pointer to another valid address likenew_arraydouble* dyn_arris a pointer. A pointer is a variable which holds a memory address. whatdyn_arr=new_arraydoes is set the memory address required to be a different one (which holds a bigger buffer).delete[ ]should be in a destructor, not in the same function asnew[ ]. But there's alreadystd::vector. so you shouldn't be reinventing dynamic arrays.new[]is a rare, primitive building block.