is there have a way the stack's initial size is 0, it should still be possible to push values onto the stack.

Here is my code:

class IntStack
{
int *p;
int top;
int maxlen;

public:
	IntStack();
	IntStack(int);
	~IntStack();
	void push(int);
	int pop();
	void push (int a[], int array_size);  
};
IntStack::IntStack(int size)
{
	maxlen=size;
	top=-1;
	p=new int[maxlen];
}

void IntStack::push(int i)
{
if(top==maxlen-1)
   {cout<<"there is full";}
   	top++;
	p[top]=i;
  }

int IntStack::pop()
{
   int V;
if(top==-1)
	{
	cout<<"There is empty\n";
	}
else
{  
   V=p[top];
   top--;
   return V;}
}

and here have some exception when i did that:

int main()
{
 IntStack stack(0);
 stack.push (1);
}

somebody know where is the problem, plz help me

The obvious stuff is wrong : use of '\n' rather than std::endl. the complete lack of tests for input values.

e.g Would this be wrong

IntStack stack(-40);

so that is why you have a problem with IntStack stack(0) since you initialize p=new int[0]; and then things are not good.....

You should have checks on all the input of the public function, that includes the constructor.

Also it is normal in stacks to have a separate top() and pop() function. That is because what should you return if the stack is empty ?

Comments
Great Explaination Along With Solution.

it looks like when you pass 0 to the constructor, that number is used as the size of your new array...

maxlen=size;
top=-1;
p=new int[maxlen];

Then you try to push 1 on to it...but it's size is zero.... or am I crazy?

i have top() and other functions and this is my assignment
some of the code i couldn't change it.
here is my assignment:
"Write a second constructor that takes a single integer specifying the stack size. Assume that memory allocation will succeed no matter how large the requested size. If the requested initial size is 0, it should still be possible to push values onto the stack. "

so any idea of how to write this constructor??
thx

Then you are going to have to declare a new array of the new size... copy the data over from the "old" array, and free the old memory.

EDIT: Alternatively, you could implement it behind the scenes as a vector instead of an array....*shrugs*

could you give me a little guide.
i am the beginner @ c++.
if this problem couldn't been solved, i couldn't do anything.
even the stack size is 0, it still could push into the int.
thx

This article has been dead for over six months. Start a new discussion instead.