Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2

Thread: stack

  1. #1
    New Coder
    Join Date
    Sep 2010
    Posts
    15
    Thanks
    1
    Thanked 0 Times in 0 Posts

    stack

    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);
    }

  • #2
    New Coder
    Join Date
    Aug 2012
    Location
    Odessa, Ukraine
    Posts
    16
    Thanks
    0
    Thanked 4 Times in 4 Posts
    Although, TOS would stand for Top Of Stack, it actually points at the bottom of stack.

    Line
    Code:
    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

    Code:
    if(p1 == (stack + SIZE))
    ...
    if(p1 == stack)
    checks.

    tl;dr a variable isn't named properly.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •