I am trying to create a calculator that keeps the order of arithmetic operations. My idea is to convert infix notation to postfix notation so that I can solve it from left to right without worrying about parentheses. Before trying to convert infix into postfix notation I wanted to solve a postfix notation exercise and I tried to use nodes to solve this, but I'm having problems with dividing the numbers and operators into a node. I am new to pointers and structs and that all things confuse me.
Here is the function that tries to divide it:
typedef char* String;
typedef struct node
{
String str;
struct node *next;
} Node;
Node *rpn_divider(String equation, int eq_size)
{
Node *rpn_parts = node_alloc(1); //pointer to first element in the node
Node *part_temp = rpn_parts; //pointer to the lattest element in the node
String temp = malloc(sizeof(char*) * NUM_SIZE);
int i, j; //i = string equation index, j = string temp index
for (i = 0, j = 0; i < eq_size; i++)
{
if (isNum(equation[i]))
temp[j++] = equation[i];
else if (isOper(equation[i]))
{
temp[0] = equation[i];
temp[1] = '\0';
next_node(part_temp, temp);
}
else
{
if (temp == '\0') continue;
temp[j] = '\0';
next_node(part_temp, temp);
j = 0;
}
}
free(part_temp->next);
free(temp);
return rpn_parts;
}
Here is the next_node function:
void next_node(Node *node, String str)
{
node->str = str;
node->next = node_alloc(1);
node = node->next;
free(str);
str = malloc(sizeof(char*) * NUM_SIZE);
str[0] = '\0';
}
and when I am trying to print the node context, it doesn't do anything:
Node *ptr;
for (ptr = head; ptr != NULL; ptr = ptr->next);
{
printf("The Str = %s", ptr->str);
}
In the next_node function, you are allocating memory and assigning it to a local copy of str. This is a memory leak and the caller will never see the new value of str. Instead you can do this:
void next_node(Node *node, String *str)
{
node->str = *str;
node->next = node_alloc(1);
node = node->next;
free(*str);
*str = malloc(sizeof(char*) * NUM_SIZE);
(*str)[0] = '\0';
}
And use it like this:
next_node(part_temp, &temp);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With