When we deallocate the original array, shouldn't we allocate it to the new higher capacity ?
What do you think lines 5 to 9 are doing?
5 6 7 8 9
int* new_arr = newint[capacity]; // create new, bigger array
for(int i = 0; i < size; ++i) { // copy elements of arr
new_arr[i] = arr[i]; // into new_arr
}
The variable new_arr is a local variable, it exists only during the lifetime of the function. When the function ends, its value would be lost. Fortunately its value is stored in arr before the function ends.
Unrelated note: the line 2 if (new_cap < capacity) return; does not return, if new_cap == capacity
That is suspicious, considering the purpose of the function.
I understand that new_arr is a temporary array that stores the values of arr and sends them back to the original array, but what I am thinking about is that,
the original array 'arr' has a certain capacity, and once you deallocate it usingdelete[] arr , every element including its size is gone except its capacity. However, the capacity has not changed! Why isn't it possible to give arr a new higher capacity ?
Also why don't we call delete[] new_arr at the end of the code to avoid leak memory or memory corruption ?
@keskiverto, I believe the condition is not suspicious since we only want to make sure the new capacity is higher than original capacity. If they are equal, then it is considered part of the else { } code afterward.
Later in the code, I have written if conditions that checks for capacity and the size of array. If (size >= capacity), then I use the resize function to increase the capacity.
I personally would say to either use malloc and realloc, or use a vector.
If you insist on doing it with the create/new/copy/delete approach, which is slow, consider if the pointers are simple types, using memcpy to do the copy at least for speed. If they are classes, this is all kinds of slow and a vector is the right answer in that case for sure.
I am not saying what you did is wrong, just my preferred approach.
Also, it is usually better to reserve tons of space up front if you know it will grow and need to re-allocate eventually, and when you re-allocate, get another large chunk of space so you don't do this often. It is absolutely a performance killer no matter what method you use, if you reallocate every time you add a couple of items to your growing list.