I'm making an RPN calc (more specifically, one that mimics unix's dc), but I can't seem to get my newvalptr to not = 0 (This means that when it pushes the value onto the stack, it's 0, instead of the result of the operation).
The weird thing is that after the line newvalptr = &newval; I tried even putting in *newvalptr = 5, and printing it out. newvalptr was still = 0, but newval was = 5...it seems that no matter what, when it's pushed on to the stack it pushes 0 (but only after doing a computation, it pushes numbers onto the stack fine before it reaches an operation
Code:
#include <stdio.h>
#include <stdlib.h> //atoi()
#include <string.h>
void push( void **stack, void *value);
void *pop( void **stack );
int main(int argc, char *argv[])
{
//create stack
void *stringStack = NULL;
int *newvalptr = NULL;
int newval = 0;
//parse input
//NOTE: only works for 2 argument operations (2+2 =?)
for (int i = 1; i < argc; i++)
{ printf("Time.\n");
if (*argv[i] == '+')
{
//bad idea...
//newval = (int *) pop(&stringStack) + (int *) pop(&stringStack);
char *val1 = pop(&stringStack);
char *val2 = pop(&stringStack);
printf("val1 = %d \n", atoi(val1));
printf("val2 = %d \n", atoi(val2));
newval = atoi(val1) + atoi(val2);
newvalptr = &newval;
//printf("newval is %d \n", *newvalptr);
printf("newval is %d \n", newval);
//push(&stringStack, newvalptr);
push(&stringStack, &newvalptr);
}
Here's my code for the stack struct, if needed:
Code:
/* STACK */
typedef struct node {
void *val;
struct node *next;
} Node;
Node *newNode( void *newval, Node *succ )
{
Node *new = malloc( sizeof(Node) );
*new = (Node){ newval, succ };
return new;
}
/* END STACK */
/* STACK METHODS */
void push( void **stack, void *value)
{
*stack = (void *) newNode( value, (Node *) *stack );
}
void *pop( void **stack )
{
Node *top = (Node *) *stack;
void *answer = top->val;
*stack = top->next;
free(top);
return answer;
}
/* END STACK METHODS */
Thanks!