02-09-2004, 06:03 AM
I made a simple LIFO push/pop stack structure in QB, and decided, for practise, to try to port it to C. Yay, I have a problem:
It issues the "Stack Empty" message too early, and then it dumps the stack incorrectly.
What's up?
Code:
/*
stack.c
demonstrates the use of a simple LIFO stack structure.
coded by Zack.
last updated: Feb 08 2004
child modules/headers: none
*/
#include <stdio.h>
#define STACKSZ 10
int spos=0; /* stack pointer */
int stack[STACKSZ]; /* the stack */
/* function prototypes */
int push (int value); /* push value onto stack */
int pop (int *dest); /* pop value into dest */
int push (int value)
{
if (spos >= (STACKSZ-1))
return -1; /* return error code */
spos++; /* increment stack pointer */
stack[spos]=value; /* push value into the stack */
return 0; /* success */
}
int pop (int *dest)
{
if (spos <= 0) /* stack empty */
return -1; /* return error code */
spos--; /* decrement stack pointer */
*dest=stack[spos]; /* pop value into dest */
return 0; /* success */
}
int main()
{
printf("Enter values seperated by the enter key to push onto the stack:\n");
int i;
int val;
while (1)
{
scanf("%d",&val);
if (push(val))
{
printf("Stack full!\n");
break;
}
}
/* dump stack */
for (i=0; i < spos; i++)
printf("%d ",stack[i]);
return 0;
}
What's up?