int *elements_temp = new int[size+1];
for (int i = 0; i <= size; i++){
elements_temp[i] = elements[i];
}
elements_temp[size + 1] = value;
You allocated elements_temp
to store size+1
integers. Valid indexes inside this array go from 0
to size
(not size+1
), as indexes are 0-based in C++.
So, you are writing outside the array bounds in the last line above. This is undefined behavior, and it's likely the cause of your problem.
What you probably want is allocating room for size+1
integers, and copying the previous integers to the new array, then add the last new element:
// Allocate room for size+1 integers:
const int newSize = size + 1;
int* elements_temp = new int[newSize];
// Copy the old array data to the new array.
// Note: i < size, *not* <= !
for (int i = 0; i < size; i++) {
elements_temp[i] = elements[i];
}
// Write the new item at the end of the array.
// Note: The index is "size", *not* "size+1"
elements_temp[size] = value;
// Update the size data member in your array class to store the new size
size = newSize;
Moreover, you should delete
the old elements
array before assigning the newly created one, e.g.:
// Get rid of old array memory
delete[] elements;
// If you don't call delete[] above, you will *leak* the old elements array
// Take ownership of the new array
elements = elements_temp;
A Better Allocation Policy
I'd like to add that, allocating a new array each time you add an item to it is a very inefficient policy. A better approach (used e.g. by the standard std::vector
container) is to allocate some memory in advance, creating a kind of available capacity, and then allocate a new array and copying the old data to the new array, only when the old vector has no more room (in other words, only when there's no more "capacity" available).
In fact, dynamic memory allocations with new[]
are expensive, and it's better to minimize them. (Although this capacity optimization may or may not be what your teacher wants from you in this learning process.)