Reputation: 93
In this implementation of stack program in C, when i print the value of pop(),why do i get that number? It should have printed '4' but instead i get an address like number. What might be the problem here?
#define MAX 5
typedef struct stack{
int data[MAX];
int top;
}stack;
int empty(stack *s){
if(s->top==-1)
return 1;
return 0;
}
int pop(stack *s){
int x;
x = s->data[s->top];
s->top = s->top -1;
return x;
}
void display(stack *s){
while(!(empty(&s)) && (s->top)!=-1){
printf("%d\n",s->data[s->top]);
s->top=s->top-1;
}
}
int main()
{
stack s;
init(&s);
push(&s,2);
push(&s,3);
push(&s,4);
display(&s);
printf("Popped element is: ");
printf("%d",pop(&s));
return 0;
}
Output:
4
3
2
Popped element is: 4200976
Process returned 0 (0x0) execution time : 0.019 s
Press any key to continue.
Upvotes: 0
Views: 87
Reputation: 311186
The function display
is invalid.
For starters this call
!(empty(&s))
has the argument type stack **
while the parameter type is stack *
. There should be
!(empty(s))
Though this check is redundant and may be removed.
And the function changes the data member top
of the stack. As result the function pop
called after the function display
has undefined behavior.
The function can look like
void display(const stack *s)
{
for ( int i = s->top; i != -1; i-- )
{
printf("%d\n",s->data[i]);
}
}
Here is a demonstrative program
#include <stdio.h>
#define MAX 5
typedef struct stack
{
int data[MAX];
int top;
} stack;
void init( stack *s )
{
s->top = -1;
}
int empty( const stack *s )
{
return s->top == -1;
}
void push( stack *s, int x )
{
if ( s->top + 1 != MAX ) s->data[++s->top] = x;
}
int pop( stack *s )
{
int x = s->data[s->top--];
return x;
}
void display(const stack *s)
{
for ( int i = s->top; i != -1; i-- )
{
printf("%d\n",s->data[i]);
}
}
int main(void)
{
stack s = { { 0 }, -1 };
init( &s );
push (&s, 2 );
push( &s, 3 );
push( &s, 4 );
display( &s );
printf( "Popped element is: " );
printf( "%d\n", pop( &s ) );
return 0;
}
It yields the expected result
4
3
2
Popped element is: 4
Upvotes: 0
Reputation: 196
After the display function your top will always have the value of -1. When using the pop function it will return the -1'th element in the array. This is undefined behaviour and so the returned x can be anything.
Upvotes: 2