While I was trying to create an array in c++ class, there arose a problem while using the constructor. Here is the code:
int stacksize = 100;
int* buffer;
int stackpointer[3]= {-1, -1, -1};
public:
threestack(int stacksize_u)
{
int buffer_u[stacksize_u*3];
this->buffer = buffer_u;
this->stacksize = stacksize_u;
}
threestack()
{
int buffer_u[(this->stacksize)*3];
this->buffer = buffer_u;
}
This actually did not work. When I create the array in the declaration, however, it worked:
int stacksize = 100;
int buffer[300];
int stackpointer[3]= {-1, -1, -1};
Can anybody tell me what is wrong while I was using the constructor?
PSS: Here is the whole class and test program:
class threestack
{
int stacksize = 100;
int* buffer;
int stackpointer[3]= {-1, -1, -1};
public:
threestack(int stacksize_u)
{
int buffer_u[stacksize_u*3];
this->buffer = buffer_u;
this->stacksize = stacksize_u;
}
threestack()
{
int buffer_u[(this->stacksize)*3];
this->buffer = buffer_u;
}
bool push(int stacknum, int value);
bool pop(int stacknum);
int peek(int stacknum);
bool empty(int stacknum);
};
bool threestack::push(int stacknum, int value)
{
if(stackpointer[stacknum-1]+1 >= stacksize)
{
cout<<"Plz do not try to push to a full stack"<<endl;
// printf("stackpointer = %d\n", stackpointer[stacknum-1]);
return 0;
}
else
{
stackpointer[stacknum-1]++;
buffer[stackpointer[stacknum-1]+(stacknum-1)*stacksize] = value;
return 1;
}
}
int threestack::peek(int stacknum)
{
if(stackpointer[stacknum-1] < 0)
{
printf("No element in stack now.\n");
return 0;
}
else
{
printf("stackpointer = %d\n", stackpointer[stacknum-1]);
return buffer[stackpointer[stacknum-1]+(stacknum-1)*stacksize];
}
}
bool threestack::pop(int stacknum)
{
if(stackpointer[stacknum-1] < 0)
{
printf("Plz do not try to pop an empty stack.\n");
return 0;
}
else
{
stackpointer[stacknum-1]--;
}
return 1;
}
bool threestack::empty(int stacknum)
{
if(stackpointer[stacknum-1] < 0)
{
return true;
}
else
{
return false;
}
}
int main(int argc, const char * argv[])
{
threestack test;
test.push(1,5);
// test.pop(1);
// test.pop(1);
int i;
for(i=0; i<101; i++)
{
test.push(2, i);
printf("%d\n", test.peek(2));
}
cout<<endl;
printf("The top of stack 1 is %d\n", test.peek(1));
// std::cout << "Hello, World!\n";
return 0;
}