Reputation: 81
I am trying to learn POO in C++. I have a problem regarding memory allocation in clases. I want to create a Stack Class. I have this code written in C++ :
This is the Stack Class :
class Stack {
private:
int *stackArray;
int topLevel;
public:
// Constructor without par
Stack() {
stackArray = new int[NMAX];
topLevel = -1; // stiva este NULL la inceput
}
Stack(int array_size) {
stackArray = new int[array_size];
topLevel = - 1;
}
~Stack() {
delete[] stackArray;
}
void push(int x) {
int n_maxim = sizeof(stackArray) / sizeof(int);
if (topLevel >= n_maxim - 1) {
cout << "The stack is full !\n";
return;
}
topLevel++;
stackArray[topLevel] = x;
}
};
And here it's the main function :
int main() {
int n;
cout << "Introduceti numarul de elemente =";
cin >> n;
Stack *s = new Stack();
s->push(6);
s->push(10);
return 0;
}
So my problem is that the memory allocation is not working, it doesnt make the 'v' array of size NMAX(100) or of size n read from the keyboard. So push function works only for 1 element because, i don't know why, sizeof(v) after any of that allocation memory is 4.
Upvotes: 0
Views: 740
Reputation: 595339
You can't use sizeof()
with a dynamically allocated array, it will return the size of the int*
pointer itself, not the size of the array it is pointing at. So your class will have to keep track of the array size.
Also, your class is not implementing the Rule of 3/5/0. You need to add a copy constructor and copy assignment operator so that you can make copies of the array properly.
Try this:
#include <algorithm>
class Stack {
private:
int *stackArray;
int arraySize;
int topLevel;
public:
Stack(int array_size = NMAX) {
stackArray = new int[array_size];
arraySize = array_size;
topLevel = -1;
}
Stack(const Stack &src) {
stackArray = new int[src.arraySize];
arraySize = src.arraySize;
for (int i = 0; i < arraySize; ++i)
stackArray[i] = src.stackArray[i];
topLevel = src.topLevel;
}
~Stack() {
delete[] stackArray;
}
Stack& operator=(const Stack &rhs) {
if (&rhs != this) {
Stack temp(rhs);
std::swap(stackArray, temp.stackArray);
std::swap(arraySize, temp.arraySize);
std::swap(topLevel, temp.topLevel);
}
return *this;
}
void push(int x) {
if (topLevel >= (arraySize-1)) {
cout << "The stack is full !\n";
return;
}
topLevel++;
stackArray[topLevel] = x;
}
};
Upvotes: 2
Reputation: 27567
You don't find the size of your stack like this:
int n_maxim = sizeof(stackArray) / sizeof(int);
because that's just the sizeof
a pointer divided by the sizeof
an int
and that'll probably be 1
.
You want something like:
class Stack {
private:
int *stackArray;
int topLevel;
int n_maxim;
public:
// Constructor without par
Stack() {
stackArray = new int[NMAX];
topLevel = -1; // stiva este NULL la inceput
n_maxim = NMAX;
}
Stack(int array_size) {
stackArray = new int[array_size];
topLevel = - 1;
n_maxim = array_size;
}
...
Upvotes: 1