I have to create a larger array doubled in size if the initial array is full, the copy all the elements of array over to the new array. After i created the new array, I insert data into the end of the array, increase the size by 1. I'm confused and was wondering if my code is correct.
1 2 3 4 5 6 7 8 9 10 11 12 13
if(arraySize == arrayCapacity){
arrayCapacity*=2;
T* temp = new T[arrayCapacity];
for(int index=0; index<arraySize; index++)
temp[i] = *(array)[i];
delete [] array;
array = temp; // array is now the same as temp array
delete [] temp;
}
array[arraySize] = data;
arraySize++;
delete [] array;
returntrue;
array, arraySize and arrayCapacity are initialized as:
1 2 3 4
arrayCapacity = 3;
arraySize = 0;
array = new T[arrayCapacity];
I have to create a my very own vector class, therefore I can't use vector.
1 2 3
delete [] temp; // I was planning to delete the temp array after copying the elements over.
delete [] array; // I had to impression that since I set array = temp there would be
memory allocated at array.
For line 7: array = temp; just to make sure, this will copy all the elements and and the new capacity of the temp array
Are arrays only dynamically allocated when I use T* array= newint[arrayCapacity] once deleted with delete [] array I will have to use new to allocate it to the heap?
Before this code the array points to memory block A.
On line 3 temp starts to point to memory block B.
The loop copies (correctly) elements from A to B.
On line 6 the array starts to point to B. Nobody points to A.
array points to B.
temp points to B.
On line 7 you do delete B.
array now points to already deallocated memory.
Nobody did deallocate A.
You have to take a different approach. Hint: T* temp = array;
You will have to either prevent copying or implement copy constructor and copy assignment.