Search code examples
cstackpostfix-notation

Why the data changed after I push the data in STACK?


This is my code of Postfix Notation function. Well, I tested several cases, and most of them worked well. But, this case below returns wrong answer. I don't know which one is wrong on my code.

=> Input Data top 100 lines 11 3 3 * 3 * 3 * 3 * 3 *

=> Solution Data top 100 lines 729

=> User Output top 100 lines -39

I debugged it several times, and I found that tmp changed "-13" after pushed it to STACK (when the calculated result of tmp is 243).

The range of M is (3 ≤ M ≤ 11 ).

#include <stdlib.h>
int M;
int STACK[13];
int ans, Sp;

void push(char c) {
    STACK[Sp++] = c;
}

int pop() {
    int n = STACK[--Sp];
    STACK[Sp] = NULL;

    return n;
}

int main() {
    int i, j, n1, n2, tmp; 
    char op;
    scanf("%d", &M);

    for (i = 0; i < M; i++) {
        scanf(" %c", &op);

        switch (op)
        {
        case '+':
            n1 = pop();
            n2 = pop();
            tmp = n1 + n2;
            break;

        case '*':
            n1 = pop();
            n2 = pop();
            tmp = n1 * n2;
            break;

        case '-':
            n1 = pop();
            n2 = pop();
            tmp = n2 - n1;
            break;

        case '/':
            n1 = pop();
            n2 = pop();
            tmp = n2 / n1;
            break;
        default:
            tmp = op - '0';
            break;
        }
        push(tmp);
    }

    ans = pop();

    printf("%d", ans);
    return 0;
}

Solution

  • Your push function is declared as:

    void push(char c)
    

    Note that the argument c is a char.

    If char is signed then it can't handle values as large as 243, its range only goes up to 127 (if using two's complement).

    You should make the argument an int:

    void push(int c)