Even if when I am pushing something, the keni(S) always returns -1. Like I can push, but when I am trying to pop, it always returns "Stack is empty!". Thanks for your time!
#include <stdio.h>
#define N 5
typedef struct{
float s[N];
int top;
}Stiva;
int keni(Stiva);
void dimiourgia(Stiva*);
void push(Stiva *, float);
float pop(Stiva *);
void dimiourgia(Stiva *St)
{
St->top = -1;
}
int keni(Stiva S)
{
if (S.top == -1)
return -1;
else
return 0;
}
void push(Stiva *St, float a)
{
if (St->top == N-1) {
printf("\n\nStack Overflow");
return;
}
else {
St->top ;
St->s[St->top] = a;
}
}
float pop(Stiva *St)
{
float c;
c = St->s[St->top];
St -> top--;
return c;
}
int main()
{
Stiva S;
float x;
int epil;
dimiourgia(&S);
do{
do{
printf("\n\n1.Push 2.Pop 3.End\n");
scanf("%d", &epil);
}while (epil<1 || epil>3);
switch (epil) {
case 1: if (S.top == N-1)
printf("\n\nStack is empty!\n\n");
else {
printf("\nPick a num\n\n");
scanf("%f", &x);
push(&S, x);
}
case 2: if (keni(S) == -1)
printf("\n\nStack is empty!\n\n");
else {
x = pop(&S);
printf("\n\n==> .2f", x);
}
}
} while(epil!=3);
return 0;
}
CodePudding user response:
anyway heres the fix
switch (epil) {
case 1: if (S.top == N-1)
printf("\n\nStack is empty!\n\n");
else {
printf("\nPick a num\n\n");
scanf("%f", &x);
push(&S, x);
}
break; <<<<==============================
case 2: if (keni(S) == -1)
printf("\n\nStack is empty!\n\n");
else {
x = pop(&S);
printf("\n\n==> .2f", x);
}
}
at the moment after you push a number you immediately pop it again
1.Push 2.Pop 3.End
1
Pick a num
42
1.Push 2.Pop 3.End
1
Pick a num
44
1.Push 2.Pop 3.End
2
==> 44.00
1.Push 2.Pop 3.End
2
==> 42.00
1.Push 2.Pop 3.End
2
Stack is empty!
1.Push 2.Pop 3.End
Found by setting a break point where you call push and simply simgle stepping and watching the code
