밑의 stack코드에서 pop을 할때 값이 제대로 안돌아 옵니다.
조회수 465회
#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("스택에 저장된 값이 없습니다.\n");
else {
printf("스택에 저장된 값 목록\n");
for (i = 0; i < top + 1; i++) {
printf("%03d : %c\n", i + 1, stack[i]);
}
printf("%d개의 값이 저장 되어 있습니다.\n", top);
}
}
void main()
{
int select = 0;
char a;
int top = -1;
char stack[MAX_STACK_SIZE];
while (select != 4) {
printf("\n1. 스택에 값 넣기\n");
printf("2. 스택에서 값 꺼내기\n");
printf("3. 스택에 저장된 값 확인\n");
printf("4. 프로그램 종료\n\n");
printf("입력 : ");
scanf_s("%d", &select);
getchar();
switch (select) {
case 1:
printf("저장할 값을 입력하세요 : ");
a=getchar();
push(&a, stack, &top);
break;
case 2:
pop(&a, stack, &top);
printf("가져온 값 -> %c", a);
break;
case 3:
showStack(stack, top);
break;
}
}
}
제목처럼 포인터 문제인지는 모르겠는데 값이 제대로 안돌아 오네요 뭐가 문제일까요?
-
(•́ ✖ •̀)
알 수 없는 사용자
1 답변
-
char pop(char *a, char *stack, int *top) { if(*top==-1) stackEmpty(); return stack[*top--]; }
연산자 우선순위에 의해서,
*top--
가*(top--)
로 동작합니다. 원하는 건(*top)--
겠죠. 이렇게 바꾸면 되네요.참고 : https://ko.cppreference.com/w/cpp/language/operator_precedence
댓글 입력