Hello folks! I am currently practicing my C skills by coding a calculator that takes infix input and turns it into postfix format then uses stack to calculate the expression.
This is the transition function that takes in infix format and outputs postfix format.
Code:
int getPriority(char* symbol){
if(!strcmp(symbol, "(")) return 0;
if(!strcmp(symbol, "+") || !strcmp(symbol, "-")) return 1;
if(!strcmp(symbol, "*") || !strcmp(symbol, "/")) return 2;
return 3;
}
char* transition(Stack *stack, char* input){
// char* postfix = (char*)malloc(sizeof(char)*10000);
// memset(postfix, 0x00, 10000);
char postfix[10000] = "";
char* token = strtok(input, " ");
while(token != NULL){
if(!strcmp(token, "(")){
push(stack, token);
}
else if(!strcmp(token, ")")){
while(strcmp(getTop(stack), "(")){
strcat(postfix, pop(stack));
strcat(postfix, " ");
}
pop(stack);
}
else if(!strcmp(token, "+") || !strcmp(token, "-") || !strcmp(token, "*") || !strcmp(token, "/")){
while(stack->top != NULL && getPriority(getTop(stack)) >= getPriority(token)){
strcat(postfix, pop(stack));
strcat(postfix, " ");
}
push(stack, token);
}
else{
strcat(postfix, token);
strcat(postfix, " ");
}
token = strtok(NULL, " ");
}
while(stack->top != NULL ){
strcat(postfix, pop(stack));
strcat(postfix, " ");
}
return postfix;
}
This function returns postfix character array, which is currently implemented in the function as
Code:
char postfix[10000] = "";
I've tried the malloc method which is right above the above code, and works equally fine.
What is the difference between these two implementations? I am suspecting that it has to do something with the memory layout of the program, since malloc will definitely create space for postfix pointer in the heap.
But I am not sure where the character array postfix will leave its mark in the memory layout. If it is stored in the stack, then I am not sure why it won't return memory error during runtime since the stack memory is freed after its return in the main function.
Thanks for helping out.