Search code examples
creturn-valuepostfix-notationpostfix-operator

postfix notation - Stack pop and push help, incorrect return value being returned for mod or pow operator


my code is relatively simple in what it aims to do, it takes in command line arguments and places the stack accordingly.

command line argument: "2 2 +" should equal 4.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

typedef struct stack {

    int top;
    int items[100];

} stack;

void initializeStack(stack* p);
void push(stack* p, int val);
int pop(stack* p);

int main(int argc, char** argv) {

    int i, a, b;
    int val = 0;
    stack ph;
    initializeStack(&ph);

    for(i=1; i<argc; i++) {
        if(strcmp(argv[i], "*") == 0) {
            a = pop(&ph);
            b = pop(&ph);
            val = a*b;
            push(&ph, val);
        }

        else if(strcmp(argv[i], "/") == 0) {
            a = pop(&ph);
            b = pop(&ph);
            val = b/a;
            push(&ph, val);
        }

        else if(strcmp(argv[i], "+") == 0) {
            a = pop(&ph);
            b = pop(&ph);
            val = a+b;
            push(&ph, val);
        }

        else if(strcmp(argv[i], "-") == 0) {
            a = pop(&ph);
            b = pop(&ph);
            val = b-a;
            push(&ph, val);
        }

        else if(strcmp(argv[i], "^") == 0) {
            a = pop(&ph);
            b = pop(&ph);
            val = pow(a,b);
            push(&ph, val);
        }

        else if(strcmp(argv[i], "%") == 0) {
            a = pop(&ph);
            b = pop(&ph);
            val = b%a;
            push(&ph, val);
        }

        else {
            push(&ph, atoi(argv[i]));
        }
    }

    printf("%d\n", pop(&ph));

    return 0;
}

void initializeStack(stack* p) {
    p->top = 0;
}

void push(stack* p, int val) {
    p->top++;
    p->items[p->top] = val;
}

int pop(stack* p) {
    int y;
    y = p->items[p->top];
    p->items[p->top] = 0;
    (p->top)--;
    return y;
}

I've tried "2 2 +" and it has worked, and so has "2 4 + 3 / 6 +", it has evaluated to 8. but then there's this problem, where "2 4 ^ 2 * 5 % 2 -" where it should evaluate to 0 but I get -2 instead. what is the flaw here?


Solution

  • as written in the comments: you have to put the * under ", otherwise it will be expanded to all files in the current folder. so cal it with

     ./a.out 2 4 ^ 2 "*" 5 % 2 -
    

    and it will work