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 +"
#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);
printf("%d\n", a);
b = pop(&ph);
printf("%d\n", b);
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(b,a);
push(&ph, val);
}
else if(strcmp(argv[i], "%") == 0) {
a = pop(&ph);
b = pop(&ph);
val = b%a;
push(&ph, val);
}
else {
push(&ph, 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 have put in printf statements in the my else if statement for addition as well as the pop at the end but if I run I get this output:
6956340 6956337 13912677
which leads me to believe it's printing memory addresses instead of the actual values that are passed in.
what would be the correct way to write my code so that if "2 2 +" was my code argument, the answer would be 4, or my current printf statements would become "2 2 4"?
You are right. Pusing pushing adresses of the argv[] strings to the stack by push(&ph, argv[i]
.
You should push(&ph, atoi(argv[i])
instead.