Qbasicnews.com

Full Version: Yeah, another problem...(C)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
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:
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;
}
It issues the "Stack Empty" message too early, and then it dumps the stack incorrectly.
What's up?
When pushing, you increment the stack pointer and then store the value. This means you skip over position zero in the stack and start at 1. You should increment after.

Leave pop the way it is.

This line:
if (spos >= (STACKSZ-1))

should be changed to this:
if (spos >= STACKSZ)

because if you think about it, spos gets incremented with every push, so it's not only a pointer, it's also the number of items that have been pushed. It will be 10 when the stack is full. So you want to check if it's >= 10, not >= 9.
Ah, okay...my stupid logic problems. :wink:
Thanks for the help. Meh, I wish C had a DIM whatever(1 to ...) option. :wink:
Meh...C :barf:

D is better. Big Grin
No, B 0wnz.
(is D a real language?)
Okay, Aga, step on up. :lol:
Is it as fast as C?
Is it as portable as C?
Does it have pointers?
What does the code look like?
Read the site for yourself Big Grin
No pointers...And C does support multimodule programs...
Zack, all *nix OSs, Windows, DOS, OS X, QNX, BeOS, HP-UX,... support C =)
Pages: 1 2