...

View Full Version : stack



digrev
07-25-2012, 05:20 PM
Hi (sorry for my english )could you please explain this if(p1==(tos+SIZE)) i think this is a control mech. but i dont understand how could it be somethink like this. i mean its suposed to be somethink like this " if(tos==(p1+SIZE))"because" tos "means top of stack and if i add size value ..it would be greater than p1 points?




#include<stdio.h>
#include<stdlib.h>
#define SIZE 10



void push(int i);
int pop(void);
int *tos,*p1,stack[SIZE];
int main(void){
int value;
p1=stack;
tos=stack;

do {
printf("ENTER VALUE");
scanf("%d",&value);
if(value!=0) push(value);
else printf("value on top %d",pop());


}while(value!=-1);

}
void push(int i){

p1++;
if(p1==(tos+SIZE)){
printf("stack overflow.\n");
exit(1);
}
*p1=i;
}
int pop(void){

if(p1==tos){

printf("stack underflow");
exit(1);
}
p1--;
return *(p1+1);
}

Bismark
08-14-2012, 12:49 PM
Although, TOS would stand for Top Of Stack, it actually points at the bottom of stack.

Line
tos=stack;
Puts a pointer to the 0th element of an array in the `tos` variable. This variable never changes, it always points to the beginning of the `stack` and check `tos + SIZE` is actually a top of stack.

Also, in this particular example, there's no need for the `tos` variable because it always equals to the `stack` pointer, so author can use


if(p1 == (stack + SIZE))
...
if(p1 == stack)

checks.

tl;dr a variable isn't named properly.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum