I initialised an array and tried displaying the elements using loop and recursion but every time it shows different values than the original ones. I tried displaying the elements individually and it works fine.
This is the class definition in which the array is defined:
class stack
{
public:
int top, *arr;
stack(int s)
{
top=-1;
size=s;
arr=def_arr(s);
}
void push(int num)
{
if(top>=size-1)
{
cout<<"Stack has reached maximum length";
}
else
{
top++;
arr[top]=num;
}
}
int pop()
{
if(top>-1)
{
int temp;
temp=arr[top];
top--;
return temp;
}
else
{
cout<<"The stack has no values";
}
}
void print()
{
if(top>-1)
{
for(int i=0; i<=top; i++)
{
cout<<arr[i];
cout<<"\t";
}
}
else
{
cout<<"Can\'t print stack of length 0";
}
}
private:
int size;
int *def_arr(int size)
{
int arr[size];
return arr;
}
};
And the code that I ran:
int main()
{
stack A(3);
A.push(5);
A.push(8);
A.push(10);
cout<<A.arr[1]<<"\n";
A.print();
}
And the result:
8
5 87 -1259567440
What am I missing?