Reputation: 115
I am implementing an ADT Stack using an array. I want to doubling the size of the array when the stack is full.
const int MAX_SIZE = 6 // max size of array stack
template<class ItemType>
class ArrayStack: public StackInterface<ItemType>{
private:
ItemType items[MAX_SIZE]; // Array of stack items
int top; // index of top
int itemCount; // Amount of items in stack
int maxsize;
This is my push method:
template<class ItemType>
bool ArrayStack<ItemType>::push(const ItemType& newEntry){
if(itemCount == maxsize){ // resize array
cout << "resizing an array..." << endl; // just for testing
ItemType* oldArray = items; // old array to be deleted
ItemType* newItems = new ItemType[2*maxsize];
for(int i=0; i<maxsize; i++){
newItems[i] = oldArray[i]; // copying all array items
}
delete[] oldArray; // deallocate
maxsize = maxsize * 2; // doubling max size
items = newItems; <- I'm getting error from this code
} // end if
// Stack is not full
top++;
items[top] = newEntry;
itemCount++;
return true;
}
I'm getting this error while I'm trying to double the size of the array:
error: array type 'int [6]' is not assignable
items = newItems;
How can I solve this?
Upvotes: 0
Views: 5310
Reputation: 597101
ItemType items[MAX_SIZE];
is a fixed array. You can't resize it, you can't reallocate it, and you certainly can't assign an ItemType*
pointer to it.
For what you are attempting to do, items
needs to be an ItemType*
pointer instead of an ItemType[]
array:
template<class ItemType>
class ArrayStack: public StackInterface<ItemType>{
private:
ItemType *items; // Array of stack items
...
};
Don't forget to initialize items
in your constructor(s), and call delete[] items;
in the destructor, and also implement proper copy/move constructors and copy/move assignment operators, per the Rule of 3/5/0.
Upvotes: 1