1

Here is the pop() function, I have written to pop an element of a stack. So far, I have succeeded in pushing elements into a stack and showing the stack. So, I guess my pop() function is doing wrong somewhere. Here is my pop function:

void pop(int newstack[], int *newtop, int bound )
{
    int item;
    if(*newtop<0)
        printf("\n CAUTION!!! UNDERFLOW");
    else
    {
        item=newstack[*newtop];
        *newtop--;
        printf("\n Element popped->%d",item);
    }
}

Taking no chance, I am also posting the show() function:

void show_stack(int newstack[], int *top)
{
    int i;
    printf("\n");
    for(i=0;i<=*top;i++)
        printf("%d",newstack[i]);
}     

I guess there is no error in the show function.

Bart
  • 19,692
  • 7
  • 68
  • 77
Mistu4u
  • 5,132
  • 15
  • 53
  • 91
  • 2
    I'm not sure this: `*newtop--;` does what you think it does. Actually I'll rephrase that. I'm *quite sure* it *doesn't* do what you think it does. – WhozCraig Sep 12 '13 at 08:35
  • You need to post your main and pop. show is not required. And *newtop--; ==> (*newtop)--; precedence matters.... – Gangadhar Sep 12 '13 at 08:38
  • @Gangadhar, error detected. See the answer. – Mistu4u Sep 12 '13 at 08:39
  • @WhozCraig : You're absolutely right. Mistu4u, you should check your pointer arithmetics. – lucasg Sep 12 '13 at 08:40
  • @Mistu4u in this case you might solved the issue by changing statement *newtop--; ==> (*newtop)--; but in actual sense you need to check your main function exactly how you are passing parameters to the function .. – Gangadhar Sep 12 '13 at 08:48
  • My 2 cent: Put all the parameter in a struct. s_stack or something similar. – mathk Sep 12 '13 at 09:16
  • Have you tried running this code step-by-step in a debugger? – PP. Sep 12 '13 at 09:36

2 Answers2

5

The * dereference / indirection operator has lower precedence than the -- postfix decrement operator. Your statement

*newtop--;

is going to be parsed as

*(newtop--);

And since the value of newtop-- is the current value of newtop, the statement achieves precisely nothing. It dereferences newtop, and does nothing with the dereferenced value.

You actually want something like this:

*newtop = *newtop - 1;

or

(*newtop)--;

See this answer for details on expressions like *newtop--.

Community
  • 1
  • 1
verbose
  • 7,827
  • 1
  • 25
  • 40
  • 1
    +1 or `--(*newtop);`, no reason to maintain the intermediate that post-dec creates. in this case its especially good, because `--*newtop` is equivalent. – WhozCraig Sep 12 '13 at 08:48
2

*newtop--; is probably wrong

Use:

(*newtop)--;

See this

Community
  • 1
  • 1
P0W
  • 46,614
  • 9
  • 72
  • 119