Thread: Stacks
View Single Post
  #4 (permalink)  
Old March 21st, 2004, 11:05 AM
davekw7x davekw7x is offline
Authorized User
 
Join Date: Feb 2004
Posts: 76
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Quote:
quote:
printf("Debug: Number of elements in stack = %d\n\n",
          sizeof(stack)/sizeof(stack[0]));

The code here does not display the number of elements in the array, but the actual limit of the array.
The code that I showed has not implemented a stack! It has reserved memory for STACK_SIZE doubles. The sizeof operator is evaluated at compile time (and therefore will not change no matter what the program does).

The program message "Number of elements in stack = 5", tells you the number of doubles that have been defined in the C array "stack".

I used your program variable names, and changed the type to "double", just to be different

Go back and change the name of the array to "double_array", instead of "stack", and change the print message to
Code:
printf("Debug: Number of elements in double_array =  %d\n\n",
          sizeof(double_array)/sizeof(double_array[0]));
Now that we have nomenclature out of the way, are you ready to implement a stack, using this array?

If you have an assignment (or a simple desire) to implement a stack, you must have some concept of what a stack is.

One way to implement a stack is to maintain a pointer (pointing to an element of your array) that points to the current "top of the stack". That is, it points to the last value that you have pushed onto the stack.

To push something on to the stack, you will increment the pointer and write the new value.

To pop something from the stack, you will read the value from the array (the element pointed to by the pointer), then decrement the pointer. There are a few more details to consider, but that's the basic idea.

Of course, your program will have to keep track of things so that you won't write to a full stack (that is, don't allow pushing anything onto the stack if it already contains STACK_SIZE elements). You also must protect against popping from an empty stack.





What operations do you need?

Here are some suggestions:

1. initialize_stack() (or, maybe flush_stack())
   This makes the stack empty.

2. push_stack(value)
   Pushes something onto the stack

3. pop_stack()
   Returns the value of the entry at the top of the stack,
   and removes that entry from the stack.

4. stack_full()
   returns 0 if the stack is not full, 1 if it is full

5. stack_empty()
   returns 0 if the stack is empty, 1 if it is not empty

Stacks are sometimes implemented as a struct whose elements
are an array, and a pointer, which is modified by pushing and popping, and points to current "top of stack".

Dave
Reply With Quote