I really don't see how this can even compile but it's so corrupted I'm sure there was a lot lost in translation. This section in particular looks off :
dectobin(int n)
{
while(n!=0)
push(n%2);
n=n/2;
while( top!=-1 )
printf("%d",pop());
stack[top]="\0" ;
}
First, there is no return type but it appears to be
void
. Worse, variable
stack
at location
top
is assigned an empty string. That is an integer value declared as
int stack[MAX]
so you can not assign a string to it. As I wrote, I don't know how this can even compile. A statement like
stack[top] = 0;
would me more appropriate there.
One other thing - this code is in dire need of limit checking and organization. Limits need to be checked because you have an array of integers of size
MAX
and a global variable is used to index into it but I see only one place where the value of that index is validated - in
pop1()
, and it's never called. You will have unpredictable results if that index ever becomes negative or it equals or exceeds
MAX
.
It needs organization because there are too many global variables. There really should not be any and for something like this there does not need to be any. All functions that operate on the stack should take that variable as an argument. In fact, you could have all of those global variables be members of a data structure and a pointer to that structure could be the argument passed to all of the functions. That would be a big improvement over what you have now. Actually, I see that you have a structure set up called a stack so you are almost ready to go. Change the type of
stck
to
int
and that will be essentially what you have with the separate items. The variables
opp1
and
opp2
should
NOT be globals because they only used locally in a couple of functions.
Here is one function converted to use the stack passed as an argument :
typedef struct stack
{
int stck[MAX];
int top;
};
void initStack( stack * pstack )
{
if( ! pstack )
return; pstack->top = -1; }
int push( stack * pstack, int x )
{
if( ! pstack )
return 0; if( pstack->top >= MAX )
return 0;
pstack->top++;
pstack->stck[ top ] = x;
return 1; }
int main(void)
{
stack s; initStack( & s ); push( & s, 42 );
return 0;
}