#include <stdio.h>
#include <stdlib.h>
#define MAX_STACK_SIZE 5
void stackFull() {
fprintf(stderr, "Stack is full, cannot add element");
exit(1);
}
void stackEmpty() {
fprintf(stderr, "Stack is Empty");
exit(1);
}
void push(char *a, char stack[], int *top)
{
if (*top >= MAX_STACK_SIZE - 1)
stackFull();
stack[++*top] = *a;
}
char pop(char *a, char *stack, int *top)
{
if(*top==-1)
stackEmpty();
return stack[*top--];
}
void showStack(char *stack, int top)
{
int i;
if (top == 0) printf ("No value stored in the stack").\n");
else {
printf ("List of values stored in the stack\n");
for (i = 0; i < top + 1; i++) {
printf("%03d : %c\n", i + 1, stack[i]);
}
printf("%d values are stored.\n", top);
}
}
void main()
{
int select = 0;
char a;
int top = -1;
char stack[MAX_STACK_SIZE];
while (select != 4) {
printf("\n1. Put value in stack\n");
printf("2. Pull value from stack\n");
printf("3. Check the value stored in the stack\n");
printf("4. Exit program\n\n");
printf ("Enter : ");
scanf_s("%d", &select);
getchar();
switch (select) {
case 1:
printf("Enter a value to save: ");"
a=getchar();
push(&a, stack, &top);
break;
case 2:
pop(&a, stack, &top);
printf("Import -> %c", a);
break;
case 3:
showStack(stack, top);
break;
}
}
}
I don't know if it's a pointer problem like the title, but the price isn't working properly. What's the problem?
data-structure c stack queue
char pop(char *a, char *stack, int *top)
{
if(*top==-1)
stackEmpty();
return stack[*top--];
}
Depending on the operator priority, *top--
operates as *(top--)
. What you want is (*top)--
. You can change it like this.
Note: https://ko.cppreference.com/w/cpp/language/operator_precedence
© 2024 OneMinuteCode. All rights reserved.